diff --git a/.gitignore b/.gitignore index 26fb9909..2db4e169 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,7 @@ **/.DS_Store **/._.DS_Store /images -phocadownload/ +/phocadownload /phocadownloadapp programmi/ pdf/ diff --git a/administrator/components/com_phocadownload/layouts/phocadownload/form/field/category.php b/administrator/components/com_phocadownload/layouts/phocadownload/form/field/category.php new file mode 100644 index 00000000..1dc22951 --- /dev/null +++ b/administrator/components/com_phocadownload/layouts/phocadownload/form/field/category.php @@ -0,0 +1,118 @@ + + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +defined('_JEXEC') or die; + +use Joomla\CMS\Factory; +use Joomla\CMS\HTML\HTMLHelper; +use Joomla\CMS\Language\Text; + +extract($displayData); + +/** + * Layout variables + * ----------------- + * @var string $autocomplete Autocomplete attribute for the field. + * @var boolean $autofocus Is autofocus enabled? + * @var string $class Classes for the input. + * @var string $description Description of the field. + * @var boolean $disabled Is this field disabled? + * @var string $group Group the field belongs to. section in form XML. + * @var boolean $hidden Is this field hidden in the form? + * @var string $hint Placeholder for the field. + * @var string $id DOM id of the field. + * @var string $label Label of the field. + * @var string $labelclass Classes to apply to the label. + * @var boolean $multiple Does this field support multiple values? + * @var string $name Name of the input field. + * @var string $onchange Onchange attribute for the field. + * @var string $onclick Onclick attribute for the field. + * @var string $pattern Pattern (Reg Ex) of value of the form field. + * @var boolean $readonly Is this field read only? + * @var boolean $repeat Allows extensions to duplicate elements. + * @var boolean $required Is this field required? + * @var integer $size Size attribute of the input. + * @var boolean $spellcheck Spellcheck state for the form field. + * @var string $validate Validation rules to apply. + * @var string $value Value attribute of the field. + * @var array $options Options available for this field. + * @var string $dataAttribute Miscellaneous data attributes preprocessed for HTML output + * @var array $dataAttributes Miscellaneous data attribute for eg, data-* + */ + +$html = array(); +$attr = ''; + +// Initialize the field attributes. +$attr .= !empty($size) ? ' size="' . $size . '"' : ''; +$attr .= $multiple ? ' multiple' : ''; +$attr .= $autofocus ? ' autofocus' : ''; +$attr .= $onchange ? ' onchange="' . $onchange . '"' : ''; +$attr .= $dataAttribute; + +// To avoid user's confusion, readonly="readonly" should imply disabled="disabled". +if ($readonly || $disabled) { + $attr .= ' disabled="disabled"'; +} + +$attr2 = ''; +$attr2 .= !empty($class) ? ' class="' . $class . '"' : ''; +$attr2 .= ' placeholder="' . $this->escape($hint ?: Text::_('JGLOBAL_TYPE_OR_SELECT_SOME_OPTIONS')) . '" '; + +if ($required) { + $attr .= ' required class="required"'; + $attr2 .= ' required'; +} + +// Create a read-only list (no name) with hidden input(s) to store the value(s). +if ($readonly) { + $html[] = HTMLHelper::_('select.genericlist', $options, '', trim($attr), 'value', 'text', $value, $id); + + // E.g. form field type tag sends $this->value as array + if ($multiple && is_array($value)) { + if (!count($value)) { + $value[] = ''; + } + + foreach ($value as $val) { + $html[] = ''; + } + } else { + $html[] = ''; + } +} else // Create a regular list. +{ + $html[] = HTMLHelper::_('select.genericlist', $options, $name, trim($attr), 'value', 'text', $value, $id); +} + +if ($refreshPage === true && $hasCustomFields) { + $attr2 .= ' data-refresh-catid="' . $refreshCatId . '" data-refresh-section="' . $refreshSection . '"'; + $attr2 .= ' onchange="Joomla.categoryHasChanged(this)"'; + + Factory::getDocument()->getWebAssetManager() + ->registerAndUseScript('field.category-change', 'layouts/joomla/form/field/category-change.min.js', [], ['defer' => true], ['core']) + ->useScript('webcomponent.core-loader'); + + // Pass the element id to the javascript + Factory::getDocument()->addScriptOptions('category-change', $id); +} else { + $attr2 .= $onchange ? ' onchange="' . $onchange . '"' : ''; +} + +Text::script('JGLOBAL_SELECT_NO_RESULTS_MATCH'); +Text::script('JGLOBAL_SELECT_PRESS_TO_SELECT'); + +Factory::getApplication()->getDocument()->getWebAssetManager() + ->usePreset('choicesjs') + ->useScript('webcomponent.field-fancy-select'); + +?> + +> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/access/access.php b/administrator/components/com_phocadownload/libraries/phocadownload/access/access.php new file mode 100644 index 00000000..b3d98b19 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/access/access.php @@ -0,0 +1,176 @@ +setQuery($query, 0, 1); + $output = $db->loadObject(); + return $output; + } + + public static function getCategoryAccessByFileId($id) { + + $output = array(); + $db = Factory::getDBO(); + $query = 'SELECT c.access, c.uploaduserid, c.deleteuserid' . + ' FROM #__phocadownload_categories AS c' . + ' LEFT JOIN #__phocadownload as a ON a.catid = c.id' . + ' WHERE a.id = '. (int) $id . + ' ORDER BY c.id'; + $db->setQuery($query, 0, 1); + $output = $db->loadObject(); + return $output; + } + + + + /** + * Method to check if the user have access to category + * Display or hide the not accessible categories - subcat folder will be not displayed + * Check whether category access level allows access + * + * E.g.: Should the link to Subcategory or to Parentcategory be displayed + * E.g.: Should the delete button displayed, should be the upload button displayed + * + * @param string $params rightType: accessuserid, uploaduserid, deleteuserid - access, upload, delete right + * @param int $params rightUsers - All selected users which should have the "rightType" right + * @param int $params rightGroup - All selected Groups of users(public, registered or special ) which should have the "rT" right + * @param int $params userAID - Specific group of user who display the category in front (public, special, registerd) + * @param int $params userId - Specific id of user who display the category in front (1,2,3,...) + * @param int $params Additional param - e.g. $display_access_category (Should be unaccessed category displayed) + * @return boolean 1 or 0 + * $rightUsers -> $userId + * $rightGroup -> $userAID + */ + + + + public static function getUserRight($rightType = 'accessuserid', $rightUsers = array(), $rightGroup = 0, $userAID = array(), $userId = 0 , $additionalParam = 0 ) { + + $user = Factory::getUser(); + // we can get the variables here, not before function call + $userAID = $user->getAuthorisedViewLevels(); + $userId = $user->get('id', 0); + + $guest = 0; + if (isset($user->guest) && $user->guest == 1) { + $guest = 1; + } + + // User ACL + $rightGroupAccess = 0; + // User can be assigned to different groups + foreach ($userAID as $keyUserAID => $valueUserAID) { + if ((int)$rightGroup == (int)$valueUserAID) { + $rightGroupAccess = 1; + break; + } + } + ; + + $rightUsersIdArray = array(); + if (!empty($rightUsers)) { + $rightUsersIdArray = explode( ',', trim( $rightUsers ) ); + } else { + $rightUsersIdArray = array(); + } + + $rightDisplay = 1; + if ($additionalParam == 0) { // We want not to display unaccessable categories ($display_access_category) + if ($rightGroup != 0) { + + if ($rightGroupAccess == 0) { + $rightDisplay = 0; + } else { // Access level only for one registered user + if (!empty($rightUsersIdArray)) { + // Check if the user is contained in selected array + $userIsContained = 0; + foreach ($rightUsersIdArray as $key => $value) { + if ($userId == $value) { + $userIsContained = 1;// check if the user id is selected in multiple box + break;// don't search again + } + // for access (-1 not selected - all registered, 0 all users) + if ($value == -1) { + if ($guest == 0) { + $userIsContained = 1;// in multiple select box is selected - All registered users + } + break;// don't search again + } + } + + if ($userIsContained == 0) { + $rightDisplay = 0; + } + } else { + + // Access rights (Default open for all) + // Upload and Delete rights (Default closed for all) + switch ($rightType) { + case 'accessuserid': + $rightDisplay = 1; + break; + + Default: + $rightDisplay = 0; + break; + } + } + } + } + } + return $rightDisplay; + } + + + /* + * + */ + public static function getNeededAccessLevels() { + + $paramsC = ComponentHelper::getParams('com_phocadownload'); + $registeredAccessLevel = $paramsC->get( 'registered_access_level', array(2,3,4) ); + return $registeredAccessLevel; + } + + /* + * Check if user's groups access rights (e.g. user is public, registered, special) can meet needed Levels + */ + + public static function isAccess($userLevels, $neededLevels) { + + $rightGroupAccess = 0; + + // User can be assigned to different groups + foreach($userLevels as $keyuserLevels => $valueuserLevels) { + foreach($neededLevels as $keyneededLevels => $valueneededLevels) { + + if ((int)$valueneededLevels == (int)$valueuserLevels) { + $rightGroupAccess = 1; + break; + } + } + if ($rightGroupAccess == 1) { + break; + } + } + return (boolean)$rightGroupAccess; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/access/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/access/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/access/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/category/category.php b/administrator/components/com_phocadownload/libraries/phocadownload/category/category.php new file mode 100644 index 00000000..e441a681 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/category/category.php @@ -0,0 +1,275 @@ +text; + + if (isset($key->parent_id) && $key->parent_id == $id && $currentId != $id && $currentId != $key->value) { + $tree[$key->value] = new CMSObject(); + $tree[$key->value]->text = $show_text; + $tree[$key->value]->value = $key->value; + $tree = PhocaDownloadCategory::CategoryTreeOption($data, $tree, $key->value, $show_text . " - ", $currentId ); + } + } + return($tree); + } + + public static function filterCategory($query, $active = NULL, $frontend = NULL, $onChange = TRUE, $fullTree = NULL ) { + + $db = Factory::getDBO(); + + $form = 'adminForm'; + if ($frontend == 1) { + $form = 'phocadownloadfilesform'; + } + + if ($onChange) { + $onChO = 'class="form-select" size="1" onchange="document.'.$form.'.submit( );"'; + } else { + $onChO = 'class="form-select" size="1"'; + } + + $categories[] = HTMLHelper::_('select.option', '0', '- '.Text::_('COM_PHOCADOWNLOAD_SELECT_CATEGORY').' -'); + $db->setQuery($query); + $catData = $db->loadObjectList(); + + + + if ($fullTree) { + + // Start - remove in case there is a memory problem + $tree = array(); + $text = ''; + + $queryAll = ' SELECT cc.id AS value, cc.title AS text, cc.parent_id as parent_id' + .' FROM #__phocadownload_categories AS cc' + .' ORDER BY cc.ordering'; + $db->setQuery($queryAll); + $catDataAll = $db->loadObjectList(); + + $catDataTree = PhocaDownloadCategory::CategoryTreeOption($catDataAll, $tree, 0, $text, -1); + + $catDataTreeRights = array(); + /*foreach ($catData as $k => $v) { + foreach ($catDataTree as $k2 => $v2) { + if ($v->value == $v2->value) { + $catDataTreeRights[$k]->text = $v2->text; + $catDataTreeRights[$k]->value = $v2->value; + } + } + }*/ + + foreach ($catDataTree as $k => $v) { + foreach ($catData as $k2 => $v2) { + if ($v->value == $v2->value) { + $catDataTreeRights[$k] = new StdClass(); + $catDataTreeRights[$k]->text = $v->text; + $catDataTreeRights[$k]->value = $v->value; + } + } + } + + + + $catDataTree = array(); + $catDataTree = $catDataTreeRights; + // End - remove in case there is a memory problem + + // Uncomment in case there is a memory problem + //$catDataTree = $catData; + } else { + $catDataTree = $catData; + } + + $categories = array_merge($categories, $catDataTree ); + + $category = HTMLHelper::_('select.genericlist', $categories, 'catid', $onChO, 'value', 'text', $active); + + return $category; + } + + public static function options($type = 0) + { + if ($type == 1) { + $tree[0] = new CMSObject(); + $tree[0]->text = Text::_('COM_PHOCADOWNLOAD_MAIN_CSS'); + $tree[0]->value = 1; + $tree[1] = new CMSObject(); + $tree[1]->text = Text::_('COM_PHOCADOWNLOAD_CUSTOM_CSS'); + $tree[1]->value = 2; + return $tree; + } + + $db = Factory::getDBO(); + + //build the list of categories + $query = 'SELECT a.title AS text, a.id AS value, a.parent_id as parent_id' + . ' FROM #__phocadownload_categories AS a' + . ' WHERE a.published = 1' + . ' ORDER BY a.ordering'; + $db->setQuery( $query ); + $items = $db->loadObjectList(); + + $catId = -1; + + $javascript = 'class="form-control" size="1" onchange="submitform( );"'; + + $tree = array(); + $text = ''; + $tree = PhocaDownloadCategory::CategoryTreeOption($items, $tree, 0, $text, $catId); + + return $tree; + + } + + public static function getCategoryByFile($id = 0) { + $db = Factory::getDBO(); + $query = 'SELECT c.id, c.title, c.alias' + . ' FROM #__phocadownload_categories AS c' + . ' LEFT JOIN #__phocadownload AS a ON a.catid = c.id' + //. ' WHERE c.published = 1' + . ' WHERE a.id ='.(int)$id + . ' ORDER BY c.id' + . ' LIMIT 1'; + $db->setQuery( $query ); + $item = $db->loadObject(); + return $item; + + } + + public static function getCategoryById($id) { + + $id = (int)$id; + if( empty(self::$categoryI[$id])) { + + $db = Factory::getDBO(); + $query = 'SELECT a.title, a.alias, a.id, a.parent_id' + . ' FROM #__phocadownload_categories AS a' + . ' WHERE a.id = '.(int)$id + . ' ORDER BY a.ordering' + . ' LIMIT 1'; + $db->setQuery( $query ); + + $category = $db->loadObject(); + if (!empty($category) && isset($category->id) && (int)$category->id > 0) { + + $query = 'SELECT a.title, a.alias, a.id, a.parent_id' + . ' FROM #__phocadownload_categories AS a' + . ' WHERE a.parent_id = '.(int)$id + . ' ORDER BY a.ordering'; + //. ' LIMIT 1'; We need all subcategories + $db->setQuery( $query ); + $subcategories = $db->loadObjectList(); + if (!empty($subcategories)) { + $category->subcategories = $subcategories; + } + } + + self::$categoryI[$id] = $category; + } + return self::$categoryI[$id]; + } + + public static function getPath($path = array(), $id = 0, $parent_id = 0, $title = '', $alias = '') { + + if( empty(self::$categoryA[$id])) { + self::$categoryP[$id] = self::getPathTree($path, $id, $parent_id, $title, $alias); + } + return self::$categoryP[$id]; + } + + public static function getPathTree($path = array(), $id = 0, $parent_id = 0, $title = '', $alias = '') { + + static $iCT = 0; + + if ((int)$id > 0) { + //$path[$iCT]['id'] = (int)$id; + //$path[$iCT]['catid'] = (int)$parent_id; + //$path[$iCT]['title'] = $title; + //$path[$iCT]['alias'] = $alias; + + $path[$id] = (int)$id. ':'. $alias; + } + + if ((int)$parent_id > 0) { + $db = Factory::getDBO(); + $query = 'SELECT a.title, a.alias, a.id, a.parent_id' + . ' FROM #__phocadownload_categories AS a' + . ' WHERE a.id = '.(int)$parent_id + . ' ORDER BY a.ordering'; + $db->setQuery( $query ); + $category = $db->loadObject(); + + if (isset($category->id)) { + $id = (int)$category->id; + $title = ''; + if (isset($category->title)) { + $title = $category->title; + } + + $alias = ''; + if (isset($category->alias)) { + $alias = $category->alias; + } + + $parent_id = 0; + if (isset($category->parent_id)) { + $parent_id = (int)$category->parent_id; + } + $iCT++; + + $path = self::getPathTree($path, (int)$id, (int)$parent_id, $title, $alias); + } + } + return $path; + } + + + private static function loadCategoriesCache(): void { + if (self::$categoriesCache === null) { + $db = Factory::getDBO(); + $db->setQuery('SELECT a.*, null AS children FROM #__phocadownload_categories AS a ORDER BY a.ordering, a.id'); + $categories = $db->loadObjectList('id') ?? []; + + array_walk($categories, function ($category) use ($categories) { + if ($category->parent_id) { + if ($categories[$category->parent_id]->children === null) + $categories[$category->parent_id]->children = []; + $categories[$category->parent_id]->children[] = $category; + } + }); + + self::$categoriesCache = $categories; + } + } + + public static function getCategories(): array { + self::loadCategoriesCache(); + + return self::$categoriesCache; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/category/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/category/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/category/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/download/download.php b/administrator/components/com_phocadownload/libraries/phocadownload/download/download.php new file mode 100644 index 00000000..1ac35c4c --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/download/download.php @@ -0,0 +1,587 @@ +getParams(); + $directLink = $fileData['directlink'];// Direct Link 0 or 1 + $externalLink = $fileData['externallink']; + $absOrRelFile = $fileData['file'];// Relative Path or Absolute Path + + // Type = 1 - Token - unique download link - cannot be direct + if ($type == 1) { + $directLink = 0; + } + + // NO FILES FOUND (abs file) + $error = false; + $error = preg_match("/COM_PHOCADOWNLOAD_ERROR/i", $absOrRelFile); + + if ($error) { + $msg = Text::_('COM_PHOCADOWNLOAD_ERROR_WHILE_DOWNLOADING_FILE') . ' ' . Text::_($absOrRelFile); + $app->enqueueMessage($msg, 'error'); + $app->redirect(Route::_($currentLink)); + } else { + + // Get extensions + $extension = File::getExt(strtolower($absOrRelFile)); + + $aft = $params->get( 'allowed_file_types_download', PhocaDownloadSettings::getDefaultAllowedMimeTypesDownload() ); + $dft = $params->get( 'disallowed_file_types_download', '' ); + + $check_http_range = $params->get( 'check_http_range', 1 ); + + // Get Mime from params ( ext --> mime) + $allowedMimeType = PhocaDownloadFile::getMimeType($extension, $aft); + $disallowedMimeType = PhocaDownloadFile::getMimeType($extension, $dft); + + // NO MIME FOUND + $errorAllowed = false;// !!! IF YES - Disallow Downloading + $errorDisallowed = false;// !!! IF YES - Allow Downloading + + $errorAllowed = preg_match("/PhocaError/i", $allowedMimeType); + $errorDisallowed = preg_match("/PhocaError/i", $disallowedMimeType); + + $ignoreDownloadCheck = $params->get( 'ignore_file_types_check', 2 ); + if ($ignoreDownloadCheck == 3 || $ignoreDownloadCheck == 4 || $ignoreDownloadCheck == 5) { + $errorAllowed = false; + $errorDisallowed = true; + } + + + if ($errorAllowed) { + $msg = Text::_('COM_PHOCADOWNLOAD_WARNFILETYPE_DOWNLOAD'); + $app->enqueueMessage($msg, 'error'); + $app->redirect(Route::_($currentLink)); + } else if (!$errorDisallowed) { + $msg = Text::_('COM_PHOCADOWNLOAD_WARNFILETYPE_DISALLOWED_DOWNLOAD'); + $app->enqueueMessage($msg, 'error'); + $app->redirect(Route::_($currentLink)); + } else { + + if ($directLink == 1) { + + // Direct Link on the same server + $fileWithoutPath = basename($absOrRelFile); + $addHit = self::hit($downloadId); + if ($type == 1) { + self::hitToken($downloadId); + } + + if ((int)$params->get('send_mail_download', 0) > 0) { + PhocaDownloadMail::sendMail((int)$params->get('send_mail_download', 0), $fileWithoutPath, 1); + } + + // USER Statistics + if ((int)$params->get('enable_user_statistics', 1) == 1) { + $addUserStat = PhocaDownloadStat::createUserStatEntry($downloadId); + } + + PhocaDownloadLog::log($downloadId, 1); + + + $app->redirect ($absOrRelFile); + exit; + } else if ($directLink == 0 && $externalLink != '') { + + // External Link but with redirect + // In case there is directLink the external Link does not go this way but directly to the external URL + $addHit = self::hit($downloadId); + if ($type == 1) { + self::hitToken($downloadId); + } + + if ((int)$params->get('send_mail_download', 0) > 0) { + PhocaDownloadMail::sendMail((int)$params->get('send_mail_download', 0), $externalLink, 1); + } + + // USER Statistics + if ((int)$params->get('enable_user_statistics', 1) == 1) { + $addUserStat = PhocaDownloadStat::createUserStatEntry($downloadId); + } + + PhocaDownloadLog::log($downloadId, 1); + + + $app->redirect ($externalLink); + exit; + + } else { + + // Clears file status cache + clearstatcache(); + + $fileWithoutPath = basename($absOrRelFile); + $fileSize = filesize($absOrRelFile); + $mimeType = ''; + $mimeType = $allowedMimeType; + + // HIT Statistics + $addHit = self::hit($downloadId); + if ($type == 1) { + self::hitToken($downloadId); + } + + if ((int)$params->get('send_mail_download', 0) > 0) { + PhocaDownloadMail::sendMail((int)$params->get('send_mail_download', 0), $fileWithoutPath, 1); + } + + // USER Statistics + if ((int)$params->get('enable_user_statistics', 1) == 1) { + $addUserStat = PhocaDownloadStat::createUserStatEntry($downloadId); + } + + PhocaDownloadLog::log($downloadId, 1); + + + if ($fileSize == 0 ) { + die(Text::_('COM_PHOCADOWNLOAD_FILE_SIZE_EMPTY')); + exit; + } + + // Clean the output buffer + ob_end_clean(); + + // test for protocol and set the appropriate headers + jimport( 'joomla.environment.uri' ); + $_tmp_uri = Uri::getInstance( Uri::current() ); + $_tmp_protocol = $_tmp_uri->getScheme(); + if ($_tmp_protocol == "https") { + // SSL Support + header('Cache-Control: private, max-age=0, must-revalidate, no-store'); + } else { + header("Cache-Control: public, must-revalidate"); + // 4.0.5 + //header('Cache-Control: pre-check=0, post-check=0, max-age=0'); + //header("Pragma: no-cache"); + header('Cache-Control: max-age=0'); + header("Expires: 0"); + } /* end if protocol https */ + header("Content-Description: File Transfer"); + header("Expires: Sat, 30 Dec 1990 07:07:07 GMT"); + header("Accept-Ranges: bytes"); + + + // HTTP Range + /* $httpRange = 0; + if(isset($_SERVER['HTTP_RANGE'])) { + list($a, $httpRange) = explode('=', $_SERVER['HTTP_RANGE']); + str_replace($httpRange, '-', $httpRange); + $newFileSize = $fileSize - 1; + $newFileSizeHR = $fileSize - $httpRange; + header("HTTP/1.1 206 Partial Content"); + header("Content-Length: ".(string)$newFileSizeHR); + header("Content-Range: bytes ".$httpRange . $newFileSize .'/'. $fileSize); + } else { + $newFileSize = $fileSize - 1; + header("Content-Length: ".(string)$fileSize); + header("Content-Range: bytes 0-".$newFileSize . '/'.$fileSize); + } + header("Content-Type: " . (string)$mimeType); + header('Content-Disposition: attachment; filename="'.$fileWithoutPath.'"'); + header("Content-Transfer-Encoding: binary\n");*/ + + // Modified by Rene + // HTTP Range - see RFC2616 for more informations (http://www.ietf.org/rfc/rfc2616.txt) + $httpRange = 0; + $newFileSize = $fileSize - 1; + // Default values! Will be overridden if a valid range header field was detected! + $resultLenght = (string)$fileSize; + $resultRange = "0-".$newFileSize; + // We support requests for a single range only. + // So we check if we have a range field. If yes ensure that it is a valid one. + // If it is not valid we ignore it and sending the whole file. + if((int)$check_http_range == 1 && isset($_SERVER['HTTP_RANGE']) && preg_match('%^bytes=\d*\-\d*$%', $_SERVER['HTTP_RANGE'])) { + // Let's take the right side + list($a, $httpRange) = explode('=', $_SERVER['HTTP_RANGE']); + // and get the two values (as strings!) + $httpRange = explode('-', $httpRange); + // Check if we have values! If not we have nothing to do! + if(!empty($httpRange[0]) || !empty($httpRange[1])) { + // We need the new content length ... + $resultLenght = $fileSize - $httpRange[0] - $httpRange[1]; + // ... and we can add the 206 Status. + header("HTTP/1.1 206 Partial Content"); + // Now we need the content-range, so we have to build it depending on the given range! + // ex.: -500 -> the last 500 bytes + if(empty($httpRange[0])) + $resultRange = $resultLenght.'-'.$newFileSize; + // ex.: 500- -> from 500 bytes to filesize + elseif(empty($httpRange[1])) + $resultRange = $httpRange[0].'-'.$newFileSize; + // ex.: 500-1000 -> from 500 to 1000 bytes + else + $resultRange = $httpRange[0] . '-' . $httpRange[1]; + //header("Content-Range: bytes ".$httpRange . $newFileSize .'/'. $fileSize); + } + } + header("Content-Length: ". $resultLenght); + header("Content-Range: bytes " . $resultRange . '/' . $fileSize); + header("Content-Type: " . (string)$mimeType); + header('Content-Disposition: attachment; filename="'.$fileWithoutPath.'"'); + header("Content-Transfer-Encoding: binary\n"); + + // TEST TEMP SOLUTION - makes problems on somve server, @ added to prevent from warning + // Do problems on some servers + //@ob_end_clean(); + + //@readfile($absOrRelFile); + + // Try to deliver in chunks + if (function_exists('set_time_limit')) { + @set_time_limit(0); + } + $fp = @fopen($absOrRelFile, 'rb'); + if ($fp !== false) { + while (!feof($fp)) { + echo fread($fp, 8192); + } + fclose($fp); + } else { + @readfile($absOrRelFile); + } + flush(); + exit; + + /* + https://www.phoca.cz/forum/viewtopic.php?f=31&t=11811 + + $fp = @fopen($absOrRelFile, 'rb'); + // HTTP Range - see RFC2616 for more informations (http://www.ietf.org/rfc/rfc2616.txt) + $newFileSize = $fileSize - 1; + // Default values! Will be overridden if a valid range header field was detected! + $rangeStart = 0; + $rangeEnd = 0; + $resultLength = $fileSize; + // We support requests for a single range only. + // So we check if we have a range field. If yes ensure that it is a valid one. + // If it is not valid we ignore it and sending the whole file. + if ($fp && isset($_SERVER['HTTP_RANGE']) && preg_match('%^bytes=\d*\-\d*$%', $_SERVER['HTTP_RANGE'])) { + // Let's take the right side + list($a, $httpRange) = explode('=', $_SERVER['HTTP_RANGE']); + // and get the two values (as strings!) + $httpRange = explode('-', $httpRange); + // Check if we have values! If not we have nothing to do! + if (sizeof($httpRange) == 2) { + // Explictly convert to int + $rangeStart = intval($httpRange[0]); + $rangeEnd = intval($httpRange[1]); // Allowed to be empty == 0 + if (($rangeStart || $rangeEnd) // something actually set? + && $rangeStart < $fileSize // must be smaller + && $rangeEnd < $fileSize // must be smaller + && (!$rangeEnd || $rangeEnd > $rangeStart) // end > start, if end is set + ) { + header("HTTP/1.1 206 Partial Content"); + if (!$rangeEnd) { + $resultLength = $fileSize - $rangeStart; + $range = $rangeStart . "-" . ($fileSize - 1) . "/" . $fileSize; + } else { + $resultLength = ($rangeEnd - $rangeStart 1); + $range = $rangeStart . "-" . $rangeEnd . "/" . $fileSize; + } + header("Content-Range: bytes " . $range); + } else { + // Didn't validate: kill + $rangeStart = 0; + $rangeEnd = 0; + } + } + } + + header("Content-Length: ". $resultLength); + header("Content-Type: " . (string)$mimeType); + header('Content-Disposition: attachment; filename="'.$fileWithoutPath.'"'); + header("Content-Transfer-Encoding: binary\n"); + @@ -211,13 +198,25 @@ class PhocaDownloadAccessFront + + // Try to deliver in chunks + @set_time_limit(0); + if ($fp !== false) { + if ($rangeStart) { + // Need to pass only part of the file, starting at $rangeStart + fseek($fp, $rangeStart, SEEK_SET); + } + // If $rangeEnd is open ended (0, whole file from $rangeStart) try fpassthru, + // else send in small chunks + if ($rangeEnd || @!fpassthru($fp)) { + while ($resultLength > 0 && !feof($fp)) { + // 4 * 1460 (default MSS with ethernet 1500 MTU) + // This is optimized for network packets, not disk access + $bytes = min(5840, $resultLength); + echo fread($fp, $bytes); + $resultLength = $resultLength - $bytes; + } + } + fclose($fp); + } else { + // Ranges are disabled at this point and were never set up + @readfile($absOrRelFile); + } + flush(); + exit; + */ + } + } + + } + return false; + + } + + public static function getDownloadData($id, $return, $type = 0) { + + $outcome = array(); + $wheres = array(); + $db = Factory::getDBO(); + $app = Factory::getApplication(); + $params = $app->getParams(); + $user = Factory::getUser(); + $redirectUrl= urlencode(base64_encode($return)); + $returnUrl = 'index.php?option=com_users&view=login&return='.$redirectUrl; + + $userLevels = implode (',', $user->getAuthorisedViewLevels()); + + $limitEnabled = $params->get( 'user_files_max_count_download', 0 ); + if ((int)$limitEnabled > 0) { + if ((int)$user->id < 1) { + $app->enqueueMessage(Text::_("COM_PHOCADOWNLOAD_NOT_LOGGED_IN_USERS_NOT_ALLOWED_DOWNLOAD"), 'error'); + $app->redirect(Route::_($returnUrl, false)); + exit; + } + $userFileCount = PhocaDownloadStat::getCountFilePerUser($id); + (int)$userFileCount++;// Because we need to count this attempt too. + if ((int)$userFileCount > (int)$limitEnabled) { + $app->enqueueMessage(Text::_("COM_PHOCADOWNLOAD_MAX_LIMIT_DOWNLOAD_PER_FILE_REACHED"), 'error'); + $app->redirect(Route::_($returnUrl, false)); + exit; + } + } + + + + + $pQ = $params->get( 'enable_plugin_query', 0 ); + + $wheres[] = " c.id = ".(int)$id; + $wheres[] = " c.published = 1"; + $wheres[] = " c.approved = 1"; + $wheres[] = " c.catid = cc.id"; + + if ($type == 1) { + // Unique download link does not have any access + $rightDisplay = 1; + + } else { + $wheres[] = " cc.access IN (".$userLevels.")"; + } + + // Active + $jnow = Factory::getDate(); + $now = $jnow->toSql(); + $nullDate = $db->getNullDate(); + $wheres[] = ' ( c.publish_up = '.$db->Quote($nullDate).' OR c.publish_up <= '.$db->Quote($now).' )'; + $wheres[] = ' ( c.publish_down = '.$db->Quote($nullDate).' OR c.publish_down >= '.$db->Quote($now).' )'; + + if ($pQ == 1) { + // GWE MOD - to allow for access restrictions + PluginHelper::importPlugin("phoca"); + //$dispatcher = JEventDispatcher::getInstance(); + $joins = array(); + $results = Factory::getApplication()->triggerEvent('onGetDownload', array (&$wheres, &$joins,$id, $paramsC)); + // END GWE MOD + } + + /*$query = " SELECT c.filename, c.directlink, c.access" + ." FROM #__phocadownload AS c" + . ($pQ == 1 ? ((count($joins)>0?( " LEFT JOIN " .implode( " LEFT JOIN ", $joins )):"")):"") // GWE MOD + . " WHERE " . implode( " AND ", $wheres ) + . " ORDER BY c.ordering";*/ + + + $query = ' SELECT c.id, c.catid, c.filename, c.directlink, c.link_external, c.access, c.confirm_license, c.metakey, c.metadesc, cc.access as cataccess, cc.accessuserid as cataccessuserid, c.tokenhits ' + .' FROM #__phocadownload AS c, #__phocadownload_categories AS cc ' + . ($pQ == 1 ? ((count($joins)>0?( ' LEFT JOIN ' .implode( ' LEFT JOIN ', $joins )):'')):'') // GWE MOD + . ' WHERE ' . implode( ' AND ', $wheres ) + . ' ORDER BY c.ordering'; + + $db->setQuery( $query , 0, 1 ); + $filename = $db->loadObjectList(); + + $limitTokenEnabled = $params->get( 'token_files_max_count_download', 0 ); + if ((int)$limitTokenEnabled > 0) { + if (isset($filename[0]->tokenhits)) { + $tokenFileCount = $filename[0]->tokenhits; + (int)$tokenFileCount++;// Because we need to count this attempt too. + if ((int)$tokenFileCount > (int)$limitTokenEnabled) { + $app->enqueueMessage(Text::_("COM_PHOCADOWNLOAD_MAX_LIMIT_DOWNLOAD_TOKEN_REACHED"), 'error'); + $app->redirect(Route::_(htmlspecialchars($return))); + exit; + } + } + } + + + //OSE Modified Start; + if (!empty($filename[0])) { + phocadownloadimport('phocadownload.utils.external'); + PhocaDownloadExternal::checkOSE($filename[0]); + } + //OSE Modified End; + + + // - - - - - - - - - - - - - - - + // USER RIGHT - Access of categories (if file is included in some not accessed category) - - - - - + // ACCESS is handled in SQL query, ACCESS USER ID is handled here (specific users) + + $rightDisplay = 0; + if ($type == 1) { + // Unique download link does not have any access + $rightDisplay = 1; + + } else { + + if (!empty($filename[0])) { + $rightDisplay = PhocaDownloadAccess::getUserRight('accessuserid', $filename[0]->cataccessuserid, $filename[0]->cataccess, $user->getAuthorisedViewLevels(), $user->get('id', 0), 0); + } + // - - - - - - - - - - - - - - - - - - - - - - + if ($rightDisplay == 0) { + $app->enqueueMessage(Text::_("COM_PHOCADOWNLOAD_NO_RIGHTS_ACCESS_CATEGORY_FILE"), 'error'); + $app->redirect(Route::_($returnUrl, false)); + exit; + } + + } + + + + + + if (empty($filename)) { + $outcome['file'] = "COM_PHOCADOWNLOAD_ERROR_NO_DB_RESULT"; + $outcome['directlink'] = 0; + $outcome['externallink'] = 0; + return $outcome; + } + + if ($type == 1) { + // Unique download link + } else { + if (isset($filename[0]->access)) { + if (!in_array($filename[0]->access, $user->getAuthorisedViewLevels())) { + $app->enqueueMessage(Text::_("COM_PHOCADOWNLOAD_PLEASE_LOGIN_DOWNLOAD_FILE"), 'error'); + $app->redirect(Route::_($returnUrl, false)); + exit; + } + } else { + $outcome['file'] = "COM_PHOCADOWNLOAD_ERROR_NO_DB_RESULT"; + $outcome['directlink'] = 0; + $outcome['externallink'] = 0; + return $outcome; + } + } + // - - - - - - - - - - - - - - - - + + + $filenameT = $filename[0]->filename; + $directlinkT = $filename[0]->directlink; + $linkExternalT = $filename[0]->link_external; + + // Unique Download Link + if ($type == 1) { + $directlinkT = 0;// Unique Download Link cannot work with direct link + } + + $filePath = PhocaDownloadPath::getPathSet('file'); + + if ($filenameT !='') { + + // Important - you cannot use direct link if you have selected absolute path + // Absolute Path defined by user + $absolutePath = $params->get( 'absolute_path', '' ); + if ($absolutePath != '') { + $directlinkT = 0; + } + + if ($directlinkT == 1 ) { + $relFile = Uri::base(true).'/'.$params->get('download_folder', 'phocadownload' ).'/'.$filenameT; + $outcome['file'] = $relFile; + $outcome['directlink'] = $directlinkT; + $outcome['externallink']= $linkExternalT; + return $outcome; + } else if ($directlinkT == 0 && $linkExternalT != '' ) { + $relFile = Uri::base(true).'/'.$params->get('download_folder', 'phocadownload' ).'/'.$filenameT; + $outcome['file'] = $relFile; + $outcome['directlink'] = $directlinkT; + $outcome['externallink']= $linkExternalT; + return $outcome; + } else { + $absFile = str_replace('\\', '/', Path::clean($filePath['orig_abs_ds'] . $filenameT)); + } + + if (File::exists($absFile)) { + $outcome['file'] = $absFile; + $outcome['directlink'] = $directlinkT; + $outcome['externallink']= $linkExternalT; + return $outcome; + } else { + + $outcome['file'] = "COM_PHOCADOWNLOAD_ERROR_NO_ABS_FILE"; + $outcome['directlink'] = 0; + $outcome['externallink']= $linkExternalT; + return $outcome; + } + } else { + + $outcome['file'] = "COM_PHOCADOWNLOAD_ERROR_NO_DB_FILE"; + $outcome['directlink'] = 0; + $outcome['externallink']= $linkExternalT; + return $outcome; + } + } + + protected static function hit($id) { + + $app = Factory::getApplication(); + $table = Table::getInstance('PhocaDownload', 'Table'); + $table->hit($id); + return true; + } + + protected static function hitToken($id) { + $db = Factory::getDBO(); + $query = $db->getQuery(true) + ->update('#__phocadownload') + ->set($db->quoteName('tokenhits') . ' = (' . $db->quoteName('tokenhits') . ' + 1)') + ->where('id = ' . $db->quote((int)$id)); + $db->setQuery($query); + + $db->execute(); + return true; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/download/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/download/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/download/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/file/file.php b/administrator/components/com_phocadownload/libraries/phocadownload/file/file.php new file mode 100644 index 00000000..18e9f211 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/file/file.php @@ -0,0 +1,438 @@ +'; + } + + return $mime; + } + + public static function existsCss($file, $type) { + $path = self::getCSSPath($type); + if (file_exists($path.$file) && $file != '') { + return $path.$file; + } + return false; + } + + public static function getCSSPath($type, $rel = 0) { + $paths = PhocaDownloadPath::getPathMedia(); + if ($rel == 1) { + if ($type == 1) { + return $paths->media_css_rel . 'main/'; + } else { + return $paths->media_css_rel . 'custom/'; + } + } else { + if ($type == 1) { + return Path::clean($paths->media_css_abs . 'main/'); + } else { + return Path::clean($paths->media_css_abs . 'custom/'); + } + } + } + + public static function getCSSFile($id = 0, $fullPath = 0) { + if ((int)$id > 0) { + $db = Factory::getDBO(); + $query = 'SELECT a.filename as filename, a.type as type' + .' FROM #__phocadownload_styles AS a' + .' WHERE a.id = '.(int) $id + .' ORDER BY a.id'; + $db->setQuery($query, 0, 1); + $filename = $db->loadObject(); + + if (isset($filename->filename) && $filename->filename != '') { + if ($fullPath == 1 && isset($filename->type)) { + return self::getCSSPath($filename->type). $filename->filename; + } else { + return $filename->filename; + } + } + } + + return false; + } + + public static function getFileSize($filename, $readable = 1) { + + $path = PhocaDownloadPath::getPathSet(); + $fileNameAbs = Path::clean($path['orig_abs'] . '/' . $filename); + + if ($readable == 1) { + return self::getFileSizeReadable(filesize($fileNameAbs)); + } else { + return filesize($fileNameAbs); + } + } + + + + public static function getFileTime($filename, $function, $format = 'DATE_FORMAT_LC3') { + + //$format = JText::_($format); + $path = PhocaDownloadPath::getPathSet(); + $fileNameAbs = Path::clean($path['orig_abs'] . '/' . $filename); + if (File::exists($fileNameAbs)) { + switch($function) { + case 2: + $fileTime = filectime($fileNameAbs); + break; + case 3: + $fileTime = fileatime($fileNameAbs); + break; + case 1: + default: + $fileTime = filemtime($fileNameAbs); + break; + } + + $fileTime = HTMLHelper::Date($fileTime, $format); + } else { + $fileTime = ''; + } + return $fileTime; + } + + + + public static function getTitleFromFilenameWithExt (&$filename) { + $folder_array = explode('/', $filename);//Explode the filename (folder and file name) + $count_array = count($folder_array);//Count this array + $last_array_value = $count_array - 1;//The last array value is (Count array - 1) + + return $folder_array[$last_array_value]; + } + + + public static function getMimeType($extension, $params) { + + $regex_one = '/({\s*)(.*?)(})/si'; + $regex_all = '/{\s*.*?}/si'; + $matches = array(); + $count_matches = preg_match_all($regex_all,$params,$matches,PREG_OFFSET_CAPTURE | PREG_PATTERN_ORDER); + + $returnMime = ''; + + for($i = 0; $i < $count_matches; $i++) { + + $phocaDownload = $matches[0][$i][0]; + preg_match($regex_one,$phocaDownload,$phocaDownloadParts); + $values_replace = array ("/^'/", "/'$/", "/^'/", "/'$/", "/
/"); + $values = explode("=", $phocaDownloadParts[2], 2); + + foreach ($values_replace as $key2 => $values2) { + $values = preg_replace($values2, '', $values); + } + + // Return mime if extension call it + if ($extension == $values[0]) { + $returnMime = $values[1]; + } + } + + if ($returnMime != '') { + return $returnMime; + } else { + return "PhocaErrorNoMimeFound"; + } + } + + public static function getMimeTypeString($params) { + + $regex_one = '/({\s*)(.*?)(})/si'; + $regex_all = '/{\s*.*?}/si'; + $matches = array(); + $count_matches = preg_match_all($regex_all,$params,$matches,PREG_OFFSET_CAPTURE | PREG_PATTERN_ORDER); + + $extString = ''; + $mimeString = ''; + + for($i = 0; $i < $count_matches; $i++) { + + $phocaDownload = $matches[0][$i][0]; + preg_match($regex_one,$phocaDownload,$phocaDownloadParts); + $values_replace = array ("/^'/", "/'$/", "/^'/", "/'$/", "/
/"); + $values = explode("=", $phocaDownloadParts[2], 2); + + foreach ($values_replace as $key2 => $values2) { + $values = preg_replace($values2, '', $values); + } + + // Create strings + $extString .= $values[0]; + $mimeString .= $values[1]; + + $j = $i + 1; + if ($j < $count_matches) { + $extString .=','; + $mimeString .=','; + } + } + + $string = array(); + $string['mime'] = $mimeString; + $string['ext'] = $extString; + + return $string; + } + + public static function getTitleFromFilenameWithoutExt (&$filename) { + + $folder_array = explode('/', $filename);//Explode the filename (folder and file name) + $count_array = count($folder_array);//Count this array + $last_array_value = $count_array - 1;//The last array value is (Count array - 1) + + $string = false; + $string = preg_match( "/\./i", $folder_array[$last_array_value] ); + if ($string) { + return PhocaDownloadFile::removeExtension($folder_array[$last_array_value]); + } else { + return $folder_array[$last_array_value]; + } + } + + public static function getFolderFromTheFile($filename) { + + $folder_array = explode('/', $filename); + $count_array = count($folder_array);//Count this array + $last_array_value = $count_array - 1; + return str_replace($folder_array[$last_array_value], '', $filename); + } + + public static function removeExtension($file_name) { + return substr($file_name, 0, strrpos( $file_name, '.' )); + } + + public static function getExtension( $file_name ) { + return strtolower( substr( strrchr( $file_name, "." ), 1 ) ); + } + + public static function canPlay( $fileName ) { + $fileExt = PhocaDownloadFile::getExtension($fileName); + + $paramsC = ComponentHelper::getParams('com_phocadownload'); + $html5 = 1;//$paramsC->get( 'html5_play', 1 ); + + if ($html5 == 1) { + switch($fileExt) { + case 'mp3': + case 'mp4': + //case 'flv': + case 'ogg': + case 'ogv': + case 'webm': + return true; + break; + + default: + return false; + break; + } + } else { + switch($fileExt) { + case 'mp3': + case 'mp4': + case 'flv': + //case 'mov': + //case 'wmv': + return true; + break; + + default: + return false; + break; + } + } + return false; + } + + public static function canPreview( $fileName ) { + $fileExt = PhocaDownloadFile::getExtension($fileName); + + switch($fileExt) { + case 'pdf': + case 'jpeg': + case 'jpg': + case 'png': + case 'gif': + return true; + break; + + default: + return false; + break; + + } + return false; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/file/fileupload.php b/administrator/components/com_phocadownload/libraries/phocadownload/file/fileupload.php new file mode 100644 index 00000000..5a76101e --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/file/fileupload.php @@ -0,0 +1,723 @@ +get( 'multiple_upload_chunk', 0 ); + $uploadMethod = $paramsC->get( 'multiple_upload_method', 4 ); + + $overwriteExistingFiles = $paramsC->get( 'overwrite_existing_files', 0 ); + + $app->allowCache(false); + + // Chunk Files + header('Content-type: text/plain; charset=UTF-8'); + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header("Cache-Control: no-store, no-cache, must-revalidate"); + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); + + // Invalid Token + Session::checkToken( 'request' ) or jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 100, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_INVALID_TOKEN')))); + + // Set FTP credentials, if given + $ftp = ClientHelper::setCredentialsFromRequest('ftp'); + + + + $file = Factory::getApplication()->input->files->get( 'file', null, 'raw'); + //$file = JFactory::getApplication()->input->files->get( 'file', null ); + $chunk = Factory::getApplication()->input->get( 'chunk', 0, '', 'int' ); + $chunks = Factory::getApplication()->input->get( 'chunks', 0, '', 'int' ); + $folder = Factory::getApplication()->input->get( 'folder', '', '', 'path' ); + $manager = Factory::getApplication()->input->get( 'manager', 'file', '', 'string' ); + + + $path = PhocaDownloadPath::getPathSet($manager);// we use viewback to get right path + + // Make the filename safe + if (isset($file['name'])) { + $file['name'] = File::makeSafe($file['name']); + } + if (isset($folder) && $folder != '') { + $folder = $folder . '/'; + } + + $chunkEnabled = 0; + // Chunk only if is enabled and only if flash is enabled + if (($chunkMethod == 1 && $uploadMethod == 1) || ($frontEnd == 0 && $chunkMethod == 0 && $uploadMethod == 1)) { + $chunkEnabled = 1; + } + + + if (isset($file['name'])) { + + + // - - - - - - - - - - + // Chunk Method + // - - - - - - - - - - + // $chunkMethod = 1, for frontend and backend + // $chunkMethod = 0, only for backend + if ($chunkEnabled == 1) { + + // If chunk files are used, we need to upload parts to temp directory + // and then we can run e.g. the condition to recognize if the file already exists + // We must upload the parts to temp, in other case we get everytime the info + // that the file exists (because the part has the same name as the file) + // so after first part is uploaded, in fact the file already exists + // Example: NOT USING CHUNK + // If we upload abc.jpg file to server and there is the same file + // we compare it and can recognize, there is one, don't upload it again. + // Example: USING CHUNK + // If we upload abc.jpg file to server and there is the same file + // the part of current file will overwrite the same file + // and then (after all parts will be uploaded) we can make the condition to compare the file + // and we recognize there is one - ok don't upload it BUT the file will be damaged by + // parts uploaded by the new file - so this is why we are using temp file in Chunk method + $stream = Factory::getStream();// Chunk Files + $tempFolder = 'pdpluploadtmpfolder'.'/'; + //$filepathImgFinal = JPath::clean($path['orig_abs_ds'].$folder.strtolower($file['name'])); + //$filepathImgTemp = JPath::clean($path['orig_abs_ds'].$folder.$tempFolder.strtolower($file['name'])); + $filepathImgFinal = Path::clean($path['orig_abs_ds'].$folder.$file['name']); + $filepathImgTemp = Path::clean($path['orig_abs_ds'].$folder.$tempFolder.$file['name']); + $filepathFolderFinal = Path::clean($path['orig_abs_ds'].$folder); + $filepathFolderTemp = Path::clean($path['orig_abs_ds'].$folder.$tempFolder); + $maxFileAge = 60 * 60; // Temp file age in seconds + $lastChunk = $chunk + 1; + $realSize = 0; + + + + + // Get the real size - if chunk is uploaded, it is only a part size, so we must compute all size + // If there is last chunk we can computhe the whole size + if ($lastChunk == $chunks) { + if (File::exists($filepathImgTemp) && File::exists($file['tmp_name'])) { + $realSize = filesize($filepathImgTemp) + filesize($file['tmp_name']); + } + } + + // 5 minutes execution time + @set_time_limit(5 * 60);// usleep(5000); + + // If the file already exists on the server: + // - don't copy the temp file to final + // - remove all parts in temp file + // Because some parts are uploaded before we can run the condition + // to recognize if the file already exists. + + // Files should be overwritten + if ($overwriteExistingFiles == 1) { + File::delete($filepathImgFinal); + } + + if (File::exists($filepathImgFinal)) { + if($lastChunk == $chunks){ + @Folder::delete($filepathFolderTemp); + } + + + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 108, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_FILE_ALREADY_EXISTS')))); + + } + + if (!PhocaDownloadFileUpload::canUpload( $file, $errUploadMsg, $manager, $frontEnd, $chunkEnabled, $realSize )) { + + // If there is some error, remove the temp folder with temp files + if($lastChunk == $chunks){ + @Folder::delete($filepathFolderTemp); + } + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 104, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_($errUploadMsg)))); + } + + // Ok create temp folder and add chunks + if (!Folder::exists($filepathFolderTemp)) { + @Folder::create($filepathFolderTemp); + } + + // Remove old temp files + if (Folder::exists($filepathFolderTemp)) { + $dirFiles = Folder::files($filepathFolderTemp); + if (!empty($dirFiles)) { + foreach ($dirFiles as $fileS) { + $filePathImgS = $filepathFolderTemp . $fileS; + // Remove temp files if they are older than the max age + if (preg_match('/\\.tmp$/', $fileS) && (filemtime($filepathImgTemp) < time() - $maxFileAge)) { + @File::delete($filePathImgS); + } + } + } + } else { + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 100, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_FOLDER_UPLOAD_NOT_EXISTS')))); + } + + // Look for the content type header + if (isset($_SERVER["HTTP_CONTENT_TYPE"])) + $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; + + if (isset($_SERVER["CONTENT_TYPE"])) + $contentType = $_SERVER["CONTENT_TYPE"]; + + if (strpos($contentType, "multipart") !== false) { + if (isset($file['tmp_name']) && is_uploaded_file($file['tmp_name'])) { + + // Open temp file + $out = $stream->open($filepathImgTemp, $chunk == 0 ? "wb" : "ab"); + //$out = fopen($filepathImgTemp, $chunk == 0 ? "wb" : "ab"); + if ($out) { + // Read binary input stream and append it to temp file + $in = fopen($file['tmp_name'], "rb"); + if ($in) { + while ($buff = fread($in, 4096)) { + $stream->write($buff); + //fwrite($out, $buff); + } + } else { + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 101, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_OPEN_INPUT_STREAM')))); + } + $stream->close(); + //fclose($out); + @File::delete($file['tmp_name']); + } else { + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 102, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_OPEN_OUTPUT_STREAM')))); + } + } else { + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 103, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_MOVE_UPLOADED_FILE')))); + } + } else { + // Open temp file + $out = $stream->open($filepathImgTemp, $chunk == 0 ? "wb" : "ab"); + //$out = JFile::read($filepathImg); + if ($out) { + // Read binary input stream and append it to temp file + $in = fopen("php://input", "rb"); + + if ($in) { + while ($buff = fread($in, 4096)) { + $stream->write($buff); + } + } else { + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 101, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_OPEN_INPUT_STREAM')))); + } + $stream->close(); + //fclose($out); + } else { + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 102, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_OPEN_OUTPUT_STREAM')))); + } + } + + + // Rename the Temp File to Final File + if($lastChunk == $chunks){ + + /*if(($imginfo = getimagesize($filepathImgTemp)) === FALSE) { + Folder::delete($filepathFolderTemp); + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 110, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_WARNING_INVALIDIMG')))); + }*/ + + // Files should be overwritten + if ($overwriteExistingFiles == 1) { + File::delete($filepathImgFinal); + } + + if(!File::move($filepathImgTemp, $filepathImgFinal)) { + + Folder::delete($filepathFolderTemp); + + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 109, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_UNABLE_TO_MOVE_FILE') .'
' + . Text::_('COM_PHOCADOWNLOAD_CHECK_PERMISSIONS_OWNERSHIP')))); + } + + + Folder::delete($filepathFolderTemp); + } + + if ((int)$frontEnd > 0) { + return $file['name']; + } + + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'OK', 'code' => 200, + 'message' => Text::_('COM_PHOCADOWNLOAD_SUCCESS').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_FILES_UPLOADED')))); + + + } else { + // No Chunk Method + $filepathImgFinal = Path::clean($path['orig_abs_ds'].$folder.strtolower($file['name'])); + $filepathImgFinal = Path::clean($path['orig_abs_ds'].$folder.$file['name']); + $filepathFolderFinal = Path::clean($path['orig_abs_ds'].$folder); + + + + if (!PhocaDownloadFileUpload::canUpload( $file, $errUploadMsg, $manager, $frontEnd, $chunkMethod, 0 )) { + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 104, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_($errUploadMsg)))); + } + + if (File::exists($filepathImgFinal) && $overwriteExistingFiles == 0) { + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 108, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_FILE_ALREADY_EXISTS')))); + } + + + if(!File::upload($file['tmp_name'], $filepathImgFinal, false, true)) { + + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 109, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_UNABLE_TO_UPLOAD_FILE') .'
' + . Text::_('COM_PHOCADOWNLOAD_CHECK_PERMISSIONS_OWNERSHIP')))); + } + + if ((int)$frontEnd > 0) { + return $file['name']; + } + + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'OK', 'code' => 200, + 'message' => Text::_('COM_PHOCADOWNLOAD_SUCCESS').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_IMAGES_UPLOADED')))); + + + } + } else { + // No isset $file['name'] + + jexit(json_encode(array( 'jsonrpc' => '2.0', 'result' => 'error', 'code' => 104, + 'message' => Text::_('COM_PHOCADOWNLOAD_ERROR').': ', + 'details' => Text::_('COM_PHOCADOWNLOAD_ERROR_UNABLE_TO_UPLOAD_FILE')))); + } + + } + + + public static function realSingleUpload( $frontEnd = 0 ) { + + $paramsC = ComponentHelper::getParams('com_phocadownload'); + // $chunkMethod = $paramsC->get( 'multiple_upload_chunk', 0 ); + // $uploadMethod = $paramsC->get( 'multiple_upload_method', 4 ); + + $overwriteExistingFiles = $paramsC->get( 'overwrite_existing_files', 0 ); + + $app = Factory::getApplication(); + Session::checkToken( 'request' ) or jexit( 'ERROR: '. Text::_('COM_PHOCADOWNLOAD_INVALID_TOKEN')); + $app->allowCache(false); + + + $file = Factory::getApplication()->input->files->get( 'Filedata', null, 'raw'); + $folder = Factory::getApplication()->input->get( 'folder', '', '', 'path' ); + $format = Factory::getApplication()->input->get( 'format', 'html', '', 'cmd'); + $return = Factory::getApplication()->input->get( 'return-url', null, 'post', 'base64' );//includes field + $viewBack = Factory::getApplication()->input->get( 'viewback', '', '', '' ); + $manager = Factory::getApplication()->input->get( 'manager', 'file', '', 'string' ); + $tab = Factory::getApplication()->input->get( 'tab', '', '', 'string' ); + $field = Factory::getApplication()->input->get( 'field' ); + $errUploadMsg = ''; + $folderUrl = $folder; + $tabUrl = ''; + $component = Factory::getApplication()->input->get( 'option', '', '', 'string' ); + + $path = PhocaDownloadPath::getPathSet($manager);// we use viewback to get right path + + + // In case no return value will be sent (should not happen) + if ($component != '' && $frontEnd == 0) { + $componentUrl = 'index.php?option='.$component; + } else { + $componentUrl = 'index.php'; + } + if ($tab != '') { + $tabUrl = '&tab='.(string)$tab; + } + + $ftp = ClientHelper::setCredentialsFromRequest('ftp'); + + // Make the filename safe + if (isset($file['name'])) { + $file['name'] = File::makeSafe($file['name']); + } + + + if (isset($folder) && $folder != '') { + $folder = $folder . '/'; + } + + + // All HTTP header will be overwritten with js message + if (isset($file['name'])) { + $filepath = Path::clean($path['orig_abs_ds'].$folder.strtolower($file['name'])); + $filepath = Path::clean($path['orig_abs_ds'].$folder.$file['name']); + + if (!PhocaDownloadFileUpload::canUpload( $file, $errUploadMsg, $manager, $frontEnd )) { + + if ($errUploadMsg == 'COM_PHOCADOWNLOAD_WARNING_FILE_TOOLARGE') { + $errUploadMsg = Text::_($errUploadMsg) . ' ('.PhocaDownloadFileUpload::getFileSizeReadable($file['size']).')'; + } /* else if ($errUploadMsg == 'COM_PHOCADOWNLOAD_WARNING_FILE_TOOLARGE_RESOLUTION') { + $imgSize = phocadownloadImage::getImageSize($file['tmp_name']); + $errUploadMsg = Text::_($errUploadMsg) . ' ('.(int)$imgSize[0].' x '.(int)$imgSize[1].' px)'; + } */ else { + $errUploadMsg = Text::_($errUploadMsg); + } + + + if ($return) { + $app->enqueueMessage( $errUploadMsg, 'error'); + $app->redirect(base64_decode($return).'&manager='.(string)$manager.'&folder='.$folderUrl); + exit; + } else { + $app->enqueueMessage( $errUploadMsg, 'error'); + $app->redirect($componentUrl); + exit; + } + } + + if (File::exists($filepath) && $overwriteExistingFiles == 0) { + if ($return) { + $app->enqueueMessage(Text::_("COM_PHOCADOWNLOAD_FILE_ALREADY_EXISTS"), 'error'); + $app->redirect(base64_decode($return).'&manager='.(string)$manager.'&folder='.$folderUrl); + exit; + } else { + $app->enqueueMessage( Text::_('COM_PHOCADOWNLOAD_FILE_ALREADY_EXISTS'), 'error'); + $app->redirect($componentUrl); + exit; + } + } + + if (!File::upload($file['tmp_name'], $filepath, false, true)) { + if ($return) { + + $app->enqueueMessage( Text::_('COM_PHOCADOWNLOAD_ERROR_UNABLE_TO_UPLOAD_FILE'), 'error'); + $app->redirect(base64_decode($return).'&manager='.(string)$manager.'&folder='.$folderUrl); + exit; + } else { + + $app->enqueueMessage( Text::_('COM_PHOCADOWNLOAD_ERROR_UNABLE_TO_UPLOAD_FILE'), 'error'); + $app->redirect($componentUrl); + exit; + } + } else { + + if ((int)$frontEnd > 0) { + return $file['name']; + } + + if ($return) { + $app->enqueueMessage( Text::_('COM_PHOCADOWNLOAD_SUCCESS_FILE_UPLOAD')); + $app->redirect(base64_decode($return).'&manager='.(string)$manager.'&folder='.$folderUrl); + exit; + } else { + $app->enqueueMessage( Text::_('COM_PHOCADOWNLOAD_SUCCESS_FILE_UPLOAD')); + $app->redirect($componentUrl); + exit; + } + } + } else { + $msg = Text::_('COM_PHOCADOWNLOAD_ERROR_UNABLE_TO_UPLOAD_FILE'); + + if ($return) { + $app->enqueueMessage( $msg, 'error'); + $app->redirect(base64_decode($return).'&manager='.(string)$manager.'&folder='.$folderUrl); + exit; + } else { + if($viewBack != '') { + $group = PhocaDownloadSettings::getManagerGroup($manager); + $link = 'index.php?option=com_phocadownload&view=phocadownloadmanager&manager='.(string)$manager + .str_replace('&', '&', $group['c']).'&'.$tabUrl.'&folder='.$folder.'&field='.$field; + $app->enqueueMessage( $msg, 'error'); + $app->redirect($link); + } else { + $app->enqueueMessage( $msg, 'error'); + $app->redirect('index.php?option=com_phocadownload'); + } + + } + } + + } + + + + public static function canUpload( $file, &$err, $manager = '', $frontEnd = 0, $chunkEnabled = 0, $realSize = 0) { + + $paramsC = ComponentHelper::getParams( 'com_phocadownload' ); + + $enable_xss_check = $paramsC->get( 'enable_xss_check', 1); + + if ($frontEnd == 1) { + $aft = $paramsC->get( 'allowed_file_types_upload', PhocaDownloadSettings::getDefaultAllowedMimeTypesUpload() ); + $dft = $paramsC->get( 'disallowed_file_types_upload', '' ); + $allowedMimeType = PhocaDownloadFile::getMimeTypeString($aft); + $disallowedMimeType = PhocaDownloadFile::getMimeTypeString($dft); + + $ignoreUploadCh = 0; + // 1 ... upload all + // 2 ... upload admin only + // 4 ... upload and download all + // 5 ... upload and download admin only + $ignoreUploadCheck = $paramsC->get( 'ignore_file_types_check', 2 ); + if ($ignoreUploadCheck == 1 || $ignoreUploadCheck == 4 ) { + $ignoreUploadCh = 1; + } + + } else { + + $aft = $paramsC->get( 'allowed_file_types_download', PhocaDownloadSettings::getDefaultAllowedMimeTypesDownload() ); + $dft = $paramsC->get( 'disallowed_file_types_download', '' ); + $allowedMimeType = PhocaDownloadFile::getMimeTypeString($aft); + $disallowedMimeType = PhocaDownloadFile::getMimeTypeString($dft); + + $ignoreUploadCh = 0; + $ignoreUploadCheck = $paramsC->get( 'ignore_file_types_check', 2 ); + if ($ignoreUploadCheck == 1 || $ignoreUploadCheck == 4 || $ignoreUploadCheck == 2 || $ignoreUploadCheck == 5 ) { + $ignoreUploadCh = 1; + } + } + + + + $paramsL = array(); + $group = PhocaDownloadSettings::getManagerGroup($manager); + if ($group['f'] == 2) { + $paramsL['upload_extensions'] = 'gif,jpg,png,jpeg'; + $paramsL['image_extensions'] = 'gif,jpg,png,jpeg'; + $paramsL['upload_mime'] = 'image/jpeg,image/gif,image/png'; + $paramsL['upload_mime_illegal'] ='application/x-shockwave-flash,application/msword,application/excel,application/pdf,application/powerpoint,text/plain,application/x-zip,text/html'; + $paramsL['upload_ext_illegal'] = $disallowedMimeType['ext']; + } else { + $paramsL['upload_extensions'] = $allowedMimeType['ext']; + $paramsL['image_extensions'] = 'bmp,gif,jpg,png,jpeg'; + $paramsL['upload_mime'] = $allowedMimeType['mime']; + $paramsL['upload_mime_illegal'] = $disallowedMimeType['mime']; + $paramsL['upload_ext_illegal'] = $disallowedMimeType['ext']; + } + + + // The file doesn't exist + if(empty($file['name'])) { + $err = 'COM_PHOCADOWNLOAD_WARNING_INPUT_FILE_UPLOAD'; + return false; + } + // Not safe file + jimport('joomla.filesystem.file'); + if ($file['name'] !== File::makesafe($file['name'])) { + $err = 'COM_PHOCADOWNLOAD_WARNFILENAME'; + return false; + } + + $format = strtolower(File::getExt($file['name'])); + if ($ignoreUploadCh == 1) { + + } else { + + $allowable = explode( ',', $paramsL['upload_extensions']); + $notAllowable = explode( ',', $paramsL['upload_ext_illegal']); + if(in_array($format, $notAllowable)) { + $err = 'COM_PHOCADOWNLOAD_WARNFILETYPE_DISALLOWED'; + return false; + } + + + //if (!in_array($format, $allowable)) { + if ($format == '' || $format == false || (!in_array($format, $allowable))) { + $err = 'COM_PHOCADOWNLOAD_WARNFILETYPE_NOT_ALLOWED'; + return false; + } + } + + + // Max size of image + // If chunk method is used, we need to get computed size + $maxSize = $paramsC->get( 'upload_maxsize', 3145728 ); + if ((int)$frontEnd > 0) { + $maxSize = $paramsC->get( 'user_file_upload_size', 3145728 ); + } else { + $maxSize = $paramsC->get( 'upload_maxsize', 3145728 ); + } + + if ($chunkEnabled == 1) { + if ((int)$maxSize > 0 && (int)$realSize > (int)$maxSize) { + $err = 'COM_PHOCADOWNLOAD_WARNFILETOOLARGE'; + + return false; + } + } else { + if ((int)$maxSize > 0 && (int)$file['size'] > (int)$maxSize) { + $err = 'COM_PHOCADOWNLOAD_WARNFILETOOLARGE'; + + return false; + } + } + + + // User (only in ucp) - Check the size of all files by users + if ($frontEnd == 2) { + $user = Factory::getUser(); + $maxUserUploadSize = (int)$paramsC->get( 'user_files_max_size', 20971520 ); + $maxUserUploadCount = (int)$paramsC->get( 'user_files_max_count', 5 ); + $allFile = PhocaDownloadUser:: getUserFileInfo($file, $user->id); + + if ($chunkEnabled == 1) { + $fileSize = $realSize; + } else { + $fileSize = $file['size']; + } + + if ((int)$maxUserUploadSize > 0 && (int) $allFile['size'] > $maxUserUploadSize) { + $err = Text::_('COM_PHOCADOWNLOAD_WARNUSERFILESTOOLARGE'); + return false; + } + + if ((int) $allFile['count'] > $maxUserUploadCount) { + $err = Text::_('COM_PHOCADOWNLOAD_WARNUSERFILESTOOMUCH'); + return false; + } + } + + + + + // Image check + $imginfo = null; + $images = explode( ',', $paramsL['image_extensions']); + + if(in_array($format, $images)) { // if its an image run it through getimagesize + + $group = PhocaDownloadSettings::getManagerGroup($manager); + if($group['i'] == 1) { + if ($chunkEnabled != 1) { + if(($imginfo = getimagesize($file['tmp_name'])) === FALSE) { + $err = 'COM_PHOCADOWNLOAD_WARNINVALIDIMG'; + $err = $imginfo[0]; + return false; + } + } + } + } else if(!in_array($format, $images)) { // if its not an image...and we're not ignoring it + $allowed_mime = explode(',', $paramsL['upload_mime']); + $illegal_mime = explode(',', $paramsL['upload_mime_illegal']); + if(function_exists('finfo_open')) {// We have fileinfo + $finfo = finfo_open(FILEINFO_MIME); + $type = finfo_file($finfo, $file['tmp_name'], FILEINFO_MIME_TYPE); + if(strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) { + $err = 'COM_PHOCADOWNLOAD_WARNINVALIDMIME'; + return false; + } + finfo_close($finfo); + } else if(function_exists('mime_content_type')) { // we have mime magic + $type = mime_content_type($file['tmp_name']); + if(strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) { + $err = 'COM_PHOCADOWNLOAD_WARNINVALIDMIME'; + return false; + } + } + } + + // XSS Check + if ((int)$enable_xss_check == 3 || ((int)$enable_xss_check == 1 && $frontEnd > 0) || ((int)$enable_xss_check == 2 && $frontEnd == 0)) { + $xss_check = file_get_contents($file['tmp_name'], false, null, -1, 256); + $html_tags = PhocaDownloadSettings::getHTMLTagsUpload(); + foreach($html_tags as $tag) { // A tag is '' + if(stristr($xss_check, '<'.$tag.' ') || stristr($xss_check, '<'.$tag.'>')) { + $err = 'COM_PHOCADOWNLOAD_WARNIEXSS'; + return false; + } + } + } + + return true; + } + + + public static function renderFTPaccess() { + + $ftpOutput = '
' + .''. Text::_('COM_PHOCADOWNLOAD_FTP_LOGIN_LABEL').'' + .Text::_('COM_PHOCADOWNLOAD_FTP_LOGIN_DESC') + .'' + .'' + .'' + .'' + .'' + .'' + .'' + .'' + .'
'; + return $ftpOutput; + } + + public static function renderCreateFolder($sessName, $sessId, $currentFolder, $viewBack, $attribs = '') { + + if ($attribs != '') { + $attribs = '&'.$attribs; + } + + $link = Uri::base() + .'index.php?option=com_phocadownload&task=phocadownloadupload.createfolder&'. $sessName.'='.$sessId.'&' + .Session::getFormToken().'=1&viewback='.$viewBack.'&' + .'folder='.PhocaDownloadUtils::filterValue($currentFolder, 'folderpath').$attribs; + + $link = str_replace('&', '&', $link); + + $folderOutput = '
'."\n" + + .'

'.Text::_('COM_PHOCADOWNLOAD_FOLDER').'

'."\n" + .'
' + .'' + .'' + .' ' + .'
'."\n" + .HTMLHelper::_( 'form.token' ) + .'
'; + return $folderOutput; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/file/fileuploadmultiple.php b/administrator/components/com_phocadownload/libraries/phocadownload/file/fileuploadmultiple.php new file mode 100644 index 00000000..10b364ac --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/file/fileuploadmultiple.php @@ -0,0 +1,300 @@ +get( 'multiple_upload_chunk', 0 ); + $uploadMethod = $paramsC->get( 'multiple_upload_method', 4 ); + + //JHtml::_('behavior.framework', true);// Load it here to be sure, it is loaded before jquery + HTMLHelper::_('jquery.framework', false);// Load it here because of own nonConflict method (nonconflict is set below) + $document = Factory::getDocument(); + // No more used - - - - - + //$document->addScript(JUri::root(true).'/components/com_phocadownload/assets/jquery/jquery-1.6.4.min.js');//USE SYSTEM + //$nC = 'var pgJQ = jQuery.noConflict();';//SET BELOW + //$document->addScriptDeclaration($nC);//SET BELOW + // - - - - - - - - - - - - + + //$document->addScript(JUri::root(true).'/components/com_phocadownload/assets/plupload/jquery.ui.plupload/jquery.ui.plupload.js'); + + if ($uploadMethod == 2) { + //$document->addScript(JUri::root(true).'/components/com_phocadownload/assets/plupload/plupload.gears.js'); + } + if ($uploadMethod == 5) { + //$document->addScript(JUri::root(true).'/components/com_phocadownload/assets/plupload/plupload.browserplus.js'); + } + HTMLHelper::_('script', 'media/com_phocadownload/js/plupload/plupload.js'); + //if ($uploadMethod == 2) { + // $document->addScript(JUri::root(true).'/components/com_phocadownload/assets/plupload/plupload.gears.js'); + //} + //if ($uploadMethod == 3) { + // $document->addScript(JUri::root(true).'/components/com_phocadownload/assets/plupload/plupload.silverlight.js'); + //} + //if ($uploadMethod == 1) { + // $document->addScript(JUri::root(true).'/components/com_phocadownload/assets/plupload/plupload.flash.js'); + //} + if ($uploadMethod == 5) { + HTMLHelper::_('script', 'media/com_phocadownload/js/plupload/plupload.browserplus.js'); + } + if ($uploadMethod == 6) { + HTMLHelper::_('script', 'media/com_phocadownload/js/plupload/plupload.html4.js'); + } + if ($uploadMethod == 4) { + HTMLHelper::_('script', 'media/com_phocadownload/js/plupload/plupload.html5.js'); + } + HTMLHelper::_('script', 'media/com_phocadownload/js/plupload/jquery.plupload.queue/jquery.plupload.queue.js'); + HTMLHelper::_('stylesheet', 'media/com_phocadownload/js/plupload/jquery.plupload.queue/css/jquery.plupload.queue.css' ); + } + + public static function getMultipleUploadSizeFormat($size) { + $readableSize = PhocaDownloadFile::getFileSizeReadable($size, '%01.0f %s', 1); + + $readableSize = str_replace(' ', '', $readableSize); + + $readableSize = strtolower($readableSize); + return $readableSize; + } + + public function renderMultipleUploadJS($frontEnd = 0, $chunkMethod = 0) { + + $document = Factory::getDocument(); + + switch ($this->method) { + case 2: + $name = 'gears_uploader'; + $runtime = 'gears'; + break; + case 3: + $name = 'silverlight_uploader'; + $runtime = 'silverlight'; + break; + case 4: + $name = 'html5_uploader'; + $runtime = 'html5'; + break; + + case 5: + $name = 'browserplus_uploader'; + $runtime = 'browserplus'; + break; + + case 6: + $name = 'html4_uploader'; + $runtime = 'html4'; + break; + + case 1: + default: + $name = 'flash_uploader'; + $runtime = 'flash'; + break; + } + + $chunkEnabled = 0; + // Chunk only if is enabled and only if flash is enabled + if (($chunkMethod == 1 && $this->method == 1) || ($this->frontEnd == 0 && $chunkMethod == 0 && $this->method == 1)) { + $chunkEnabled = 1; + } + + + + $this->url = PhocaDownloadUtils::filterValue($this->url, 'text'); + $this->reload = PhocaDownloadUtils::filterValue($this->reload, 'text'); + $this->url = str_replace('&', '&', $this->url); + $this->reload = str_replace('&', '&', $this->reload); + + + $js = 'var pgJQ = jQuery.noConflict();'; + + $js .='pgJQ(function() {'."\n"; + + $js.=''."\n"; + $js.=' plupload.addI18n({'."\n"; + $js.=' \'Select files\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_SELECT_FILES')).'\','."\n"; + $js.=' \'Add files to the upload queue and click the start button.\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_ADD_FILES_TO_UPLOAD_QUEUE_AND_CLICK_START_BUTTON')).'\','."\n"; + $js.=' \'Filename\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_FILENAME')).'\','."\n"; + $js.=' \'Status\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_STATUS')).'\','."\n"; + $js.=' \'Size\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_SIZE')).'\','."\n"; + $js.=' \'Add files\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_ADD_FILES')).'\','."\n"; + $js.=' \'Add Files\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_ADD_FILES')).'\','."\n"; + $js.=' \'Start upload\':\''.addslashes(Text::_('COM_PHOCADOWNLOAD_START_UPLOAD')).'\','."\n"; + $js.=' \'Start Upload\':\''.addslashes(Text::_('COM_PHOCADOWNLOAD_START_UPLOAD')).'\','."\n"; + $js.=' \'Stop upload\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_STOP_CURRENT_UPLOAD')).'\','."\n"; + $js.=' \'Stop Upload\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_STOP_CURRENT_UPLOAD')).'\','."\n"; + $js.=' \'Stop current upload\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_STOP_CURRENT_UPLOAD')).'\','."\n"; + $js.=' \'Start uploading queue\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_START_UPLOADING_QUEUE')).'\','."\n"; + $js.=' \'Drag files here.\' : \''.addslashes(Text::_('COM_PHOCADOWNLOAD_DRAG_FILES_HERE')).'\''."\n"; + $js.=' });'; + $js.=''."\n"; + + + $js.=' pgJQ("#'.$name.'").pluploadQueue({'."\n"; + $js.=' runtimes : \''.$runtime.'\','."\n"; + $js.=' url : \''.$this->url.'\','."\n"; + //$js.=' max_file_size : \''.$this->maxFileSize.'\','."\n"; + + if ($this->maxFileSize != '0b') { + $js.=' max_file_size : \''.$this->maxFileSize.'\','."\n"; + } + + if ($chunkEnabled == 1) { + $js.=' chunk_size : \'1mb\','."\n"; + } + $js.=' preinit: attachCallbacks,'."\n"; + $js.=' unique_names : false,'."\n"; + $js.=' multipart: true,'."\n"; + $js.=' filters : ['."\n"; + //$js.=' {title : "'.JText::_('COM_PHOCADOWNLOAD_IMAGE_FILES').'", extensions : "jpg,gif,png"}'."\n"; + //$js.=' {title : "Zip files", extensions : "zip"}'."\n"; + $js.=' ],'."\n"; + $js.=''."\n"; + /*if ($this->method != 6) { + if ((int)$this->imageWidth > 0 || (int)$this->imageWidth > 0) { + $js.=' resize : {width : '.$this->imageWidth.', height : '.$this->imageHeight.', quality : '.$this->imageQuality.'},'."\n"; + $js.=''."\n"; + } + }*/ + if ($this->method == 1) { + //$js.=' flash_swf_url : \''.JUri::root(true).'/components/com_phocadownload/assets/plupload/plupload.flash.swf\''."\n"; + } else if ($this->method == 3) { + //$js.=' silverlight_xap_url : \''.JUri::root(true).'/components/com_phocadownload/assets/plupload/plupload.silverlight.xap\''."\n"; + } + $js.=' });'."\n"; + + $js.=''."\n"; + + $js.='function attachCallbacks(Uploader) {'."\n"; + $js.=' Uploader.bind(\'FileUploaded\', function(Up, File, Response) {'."\n"; + $js.=' var obj = eval(\'(\' + Response.response + \')\');'."\n"; + //if ($this->method == 4 || $this->method == 6) { + if ($this->method == 6) { + $js.=' var queueFiles = Uploader.total.failed + Uploader.total.uploaded;'."\n"; + $js.=' var uploaded0 = Uploader.total.uploaded;'."\n"; + } else { + $js.=' var queueFiles = Uploader.total.failed + Uploader.total.uploaded + 1;'."\n"; + $js.=' var uploaded0 = Uploader.total.uploaded + 1;'."\n"; + } + $js.=''."\n"; + $js.=' if ((typeof(obj.result) != \'undefined\') && obj.result == \'error\') {'."\n"; + $js.=' '."\n"; + if ($this->method == 6) { + //$js.=' var uploaded0 = Uploader.total.uploaded;'."\n"; + } else { + //$js.=' var uploaded0 = Uploader.total.uploaded + 1;'."\n"; + } + $js.=' Up.trigger("Error", {message : obj.message, code : obj.code, details : obj.details, file: File});'."\n"; + $js.=' if( queueFiles == Uploader.files.length) {'."\n"; + if ($this->method == 6) { + $js.=' var uploaded0 = Uploader.total.uploaded;'."\n"; + } else { + $js.=' var uploaded0 = Uploader.total.uploaded;'."\n"; + } + $js.=' window.location = \''.$this->reload.'\' + \'&muuploaded=\' + uploaded0 + \'&mufailed=\' + Uploader.total.failed;'."\n"; + //$js.=' alert(\'Error\' + obj.message)'."\n"; + $js.=' }'."\n"; + $js.=' return false; '."\n"; + $js.=''."\n"; + $js.=' } else {'."\n"; + $js.=' if( queueFiles == Uploader.files.length) {'."\n"; + //$js.=' var uploaded = Uploader.total.uploaded + 1;'."\n"; + if ($this->method == 6) { + $js.=' var uploaded = Uploader.total.uploaded;'."\n"; + } else { + $js.=' var uploaded = Uploader.total.uploaded + 1;'."\n"; + } + $js.=' window.location = \''.$this->reload.'\' + \'&muuploaded=\' + uploaded + \'&mufailed=\' + Uploader.total.failed;'."\n"; + //$js.=' alert(\'OK\' + obj.message)'."\n"; + $js.=' }'."\n"; + $js.=' }'."\n"; + $js.=' });'."\n"; + $js.=' '."\n"; + $js.=' Uploader.bind(\'Error\', function(Up, ErrorObj) {'."\n"; + $js.=''."\n"; + // $js.=' if (ErrorObj.code == 100) { '."\n"; + //$js.=' pgJQ(\'#\' + ErrorObj.file.id).append(\'
\'+ ErrorObj.message + ErrorObj.details +\'
\');'."\n"; + $js.=' pgJQ(\'#\' + ErrorObj.file.id).append(\'
\'+ ErrorObj.message + ErrorObj.details +\'
\');'."\n"; + // $js.=' }'."\n"; + $js.=' }); '."\n"; + $js.='}'; + + $js.='});'."\n";// End $(function() + + $document->addScriptDeclaration($js); + } + + public function getMultipleUploadHTML($width = '', $height = '330', $mootools = 1) { + + + switch ($this->method) { + case 2: + $name = 'gears_uploader'; + $msg = Text::_('COM_PHOCADOWNLOAD_NOT_INSTALLED_GEARS'); + break; + case 3: + $name = 'silverlight_uploader'; + $msg = Text::_('COM_PHOCADOWNLOAD_NOT_INSTALLED_SILVERLIGHT'); + break; + case 4: + $name = 'html5_uploader'; + $msg = Text::_('COM_PHOCADOWNLOAD_NOT_SUPPORTED_HTML5'); + break; + + case 5: + $name = 'browserplus_uploader'; + $msg = Text::_('COM_PHOCADOWNLOAD_NOT_INSTALLED_BROWSERPLUS'); + break; + + case 6: + $name = 'html4_uploader'; + $msg = Text::_('COM_PHOCADOWNLOAD_NOT_SUPPORTED_HTML4'); + break; + + case 1: + default: + $name = 'flash_uploader'; + $msg = Text::_('COM_PHOCADOWNLOAD_NOT_INSTALLED_FLASH'); + break; + } + + $style = ''; + if ($width != '') { + $style .= 'width: '.(int)$width.'px;'; + } + if ($height != '') { + $style .= 'height: '.(int)$height.'px;'; + } + + return '
'.$msg.'
'; + + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/file/fileuploadsingle.php b/administrator/components/com_phocadownload/libraries/phocadownload/file/fileuploadsingle.php new file mode 100644 index 00000000..35435ae7 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/file/fileuploadsingle.php @@ -0,0 +1,40 @@ +' + .''; + + } else { + $html = '' + //.'' + .'' + .'' + .''; + } + + return $html; + + } +} +?> \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/file/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/file/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/file/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/html/batch.php b/administrator/components/com_phocadownload/libraries/phocadownload/html/batch.php new file mode 100644 index 00000000..d02a5440 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/html/batch.php @@ -0,0 +1,139 @@ +setQuery( $query ); + $data = $db->loadObjectList(); + $tree = array(); + $text = ''; + $catId= -1; + $tree = PhocaDownloadCategory::CategoryTreeOption($data, $tree, 0, $text, $catId); + + if ($category == 1) { + array_unshift($tree, HTMLHelper::_('select.option', 0, Text::_('JLIB_HTML_ADD_TO_ROOT'), 'value', 'text')); + } + + + // Create the batch selector to change select the category by which to move or copy. + $lines = array( + '', + '
', + '', + HTMLHelper::_( 'select.radiolist', $options, 'batch[move_copy]', '', 'value', 'text', 'm'), + '
' + ); + + return implode("\n", $lines); + } +*/ + + private static function buildCategoryTree(array &$options, array $categories, string $treeTitle): void { + foreach ($categories as $category) { + $title = ($treeTitle ? $treeTitle . ' - ' : '') . $category->title; + $options[] = (object)[ + 'text' => $title . ($category->language === '*' ? '' : ' (' . $category->language . ')'), + 'value' => $category->id, + ]; + if ($category->children) + self::buildCategoryTree($options, $category->children, $title); + } + } + + public static function item($published, $category = 0) + { + // Create the copy/move options. + $options = array( + HTMLHelper::_('select.option', 'c', Text::_('JLIB_HTML_BATCH_COPY')), + HTMLHelper::_('select.option', 'm', Text::_('JLIB_HTML_BATCH_MOVE')) + ); + + $rootCategories = array_filter(PhocadownloadCategory::getCategories(), function($category) { + return !$category->parent_id; + }); + + $tree = []; + $tree[] = HTMLHelper::_('select.option', '', Text::_('JSELECT'), 'value', 'text'); + if ($category) { + $tree[] = HTMLHelper::_('select.option', 0, Text::_('JLIB_HTML_ADD_TO_ROOT'), 'value', 'text'); + } + self::buildCategoryTree($tree, $rootCategories, ''); + + $fancySelectData = [ + 'autocomplete' => 'off', + 'autofocus' => false, + 'class' => '', + 'description' => '', + 'disabled' => false, + 'group' => false, + 'id' => 'batch-category-id', + 'hidden' => false, + 'hint' => '', + 'label' => '', + 'labelclass' => '', + 'onchange' => '', + 'onclick' => '', + 'multiple' => false, + 'pattern' => '', + 'readonly' => false, + 'repeat' => false, + 'required' => false, + 'size' => 4, + 'spellcheck' => false, + 'validate' => '', + 'value' => '', + 'options' => $tree, + 'dataAttributes' => [], + 'dataAttribute' => '', + 'name' => 'batch[category_id]', + ]; + + // Create the batch selector to change select the category by which to move or copy. + $lines = array( + '', + '
', + LayoutHelper::render('joomla.form.field.list-fancy-select', $fancySelectData), + HTMLHelper::_( 'select.radiolist', $options, 'batch[move_copy]', '', 'value', 'text', 'm'), + '
' + ); + + return implode("\n", $lines); + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/html/grid.php b/administrator/components/com_phocadownload/libraries/phocadownload/html/grid.php new file mode 100644 index 00000000..a544756c --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/html/grid.php @@ -0,0 +1,32 @@ + array('disapprove', 'COM_PHOCADOWNLOAD_APPROVED', 'COM_PHOCADOWNLOAD_NOT_APPROVE_ITEM', 'COM_PHOCADOWNLOAD_APPROVED', false, 'publish', 'publish'), + 0 => array('approve', 'COM_PHOCADOWNLOAD_NOT_APPROVED', 'COM_PHOCADOWNLOAD_APPROVE_ITEM', 'COM_PHOCADOWNLOAD_NOT_APPROVED', false, 'unpublish', 'unpublish') + ); + return self::state($states, $value, $i, $prefix, $enabled, true, $checkbox); + } +} diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/html/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/html/index.html new file mode 100644 index 00000000..42682b47 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/html/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/html/jgrid.php b/administrator/components/com_phocadownload/libraries/phocadownload/html/jgrid.php new file mode 100644 index 00000000..f4fdbefe --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/html/jgrid.php @@ -0,0 +1,40 @@ + array('disapprove', 'COM_PHOCADOWNLOAD_APPROVED', 'COM_PHOCADOWNLOAD_NOT_APPROVE_ITEM', 'COM_PHOCADOWNLOAD_APPROVED', false, 'publish', 'publish'), + 0 => array('approve', 'COM_PHOCADOWNLOAD_NOT_APPROVED', 'COM_PHOCADOWNLOAD_APPROVE_ITEM', 'COM_PHOCADOWNLOAD_NOT_APPROVED', false, 'unpublish', 'unpublish') + ); + return self::state($states, $value, $i, $prefix, $enabled, true, $checkbox); + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/log/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/log/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/log/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/log/log.php b/administrator/components/com_phocadownload/libraries/phocadownload/log/log.php new file mode 100644 index 00000000..28fc0fa5 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/log/log.php @@ -0,0 +1,72 @@ +get('enable_logging', 0); + // No Logging + if ($logging == 0) { + return false; + } + + // Only Downloads + if ($logging == 1 && $type == 2) { + return false; + } + + // Only Uploads + if ($logging == 2 && $type == 1) { + return false; + } + + + $user = Factory::getUser(); + $uri = Uri::getInstance(); + $db = Factory::getDBO(); + + $row = Table::getInstance('PhocaDownloadLogging', 'Table'); + $data = array(); + $data['type'] = (int)$type; + $data['fileid'] = (int)$fileid; + $data['catid'] = 0;// Don't stored catid, bind the catid while displaying log + $data['userid'] = (int)$user->id; + $data['ip'] = PhocaDownloadUtils::getIp(); + $data['page'] = $uri->toString(); + $data['params'] = ''; + + if (!$row->bind($data)) { + throw new Exception($row->getError()); + return false; + } + + $jnow = Factory::getDate(); + $row->date = $jnow->toSql(); + + if (!$row->check()) { + throw new Exception($row->getError()); + return false; + } + + if (!$row->store()) { + throw new Exception($row->getError()); + return false; + } + return true; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/mail/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/mail/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/mail/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/mail/mail.php b/administrator/components/com_phocadownload/libraries/phocadownload/mail/mail.php new file mode 100644 index 00000000..6250c1a8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/mail/mail.php @@ -0,0 +1,86 @@ +get( 'sitename' ); + $mailfrom = $app->get( 'mailfrom' ); + $fromname = $sitename; + $date = HTMLHelper::_('date', gmdate('Y-m-d H:i:s'), Text::_( 'DATE_FORMAT_LC2' )); + $user = Factory::getUser(); + $params = $app->getParams(); + + if (isset($user->name) && $user->name != '') { + $name = $user->name; + } else { + $name = Text::_('COM_PHOCADOWNLOAD_ANONYMOUS'); + } + if (isset($user->username) && $user->username != '') { + $userName = ' ('.$user->username.')'; + } else { + $userName = ''; + } + + if ($method == 1) { + $subject = $sitename. ' - ' . Text::_( 'COM_PHOCADOWNLOAD_FILE_DOWNLOADED' ); + $title = Text::_( 'COM_PHOCADOWNLOAD_FILE_DOWNLOADED' ); + $messageText = Text::_( 'COM_PHOCADOWNLOAD_FILE') . ' "' .$fileName . '" '.Text::_('COM_PHOCADOWNLOAD_WAS_DOWNLOADED_BY'). ' '.$name . $userName.'.'; + } else { + $subject = $sitename. ' - ' . Text::_( 'COM_PHOCADOWNLOAD_SUCCESS_FILE_UPLOADED' ); + $title = Text::_( 'COM_PHOCADOWNLOAD_SUCCESS_NEW_FILE_UPLOADED' ); + $messageText = Text::_( 'COM_PHOCADOWNLOAD_FILE') . ' "' .$fileName . '" '.Text::_('COM_PHOCADOWNLOAD_WAS_UPLOADED_BY'). ' '.$name . $userName.'.'; + } + + //get all super administrator + $query = 'SELECT name, email, sendEmail' . + ' FROM #__users' . + ' WHERE id = '.(int)$id . + ' ORDER BY id'; + $db->setQuery( $query ); + $rows = $db->loadObjectList(); + + if (isset($rows[0]->email)) { + $email = $rows[0]->email; + } + + + $message = $title . "\n\n" + . Text::_( 'COM_PHOCADOWNLOAD_WEBSITE' ) . ': '. $sitename . "\n" + . Text::_( 'COM_PHOCADOWNLOAD_DATE' ) . ': '. $date . "\n" + . 'IP: ' . PhocaDownloadUtils::getIp(). "\n\n" + . Text::_( 'COM_PHOCADOWNLOAD_MESSAGE' ) . ': '."\n" + . "\n\n" + . $messageText + . "\n\n" + . Text::_( 'COM_PHOCADOWNLOAD_REGARDS' ) .", \n" + . $sitename ."\n"; + + $subject = html_entity_decode($subject, ENT_QUOTES); + $message = html_entity_decode($message, ENT_QUOTES); + + $mail = Factory::getMailer(); + $mail->sendMail($mailfrom, $fromname, $email, $subject, $message); + return true; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/ordering/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/ordering/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/ordering/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/ordering/ordering.php b/administrator/components/com_phocadownload/libraries/phocadownload/ordering/ordering.php new file mode 100644 index 00000000..fb4097cc --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/ordering/ordering.php @@ -0,0 +1,222 @@ +get('ordering_asc_desc_arrows', 0); + + $item_ordering_values = $paramsC->get('file_ordering_values', '1,2,3,4,5,6,11,12,15,16,13,14,9,10'); + } else { + $ordering_asc_desc_arrows = 0; + $item_ordering_values = '1,2,3,4,5,6,7,8,11,12,15,16,13,14,9,10'; + } + + if ($ordering_asc_desc_arrows == 1) { + + + $itemOrdering = array( + 1 => Text::_('COM_PHOCADOWNLOAD_ORDERING') . "  " . "⇧", + 2 => Text::_('COM_PHOCADOWNLOAD_ORDERING') . "  " . "⇩", + 3 => Text::_('COM_PHOCADOWNLOAD_TITLE') . "  " . "⇧", + 4 => Text::_('COM_PHOCADOWNLOAD_TITLE') . "  " . "⇩", + 5 => Text::_('COM_PHOCADOWNLOAD_DATE') . "  " . "⇧", + 6 => Text::_('COM_PHOCADOWNLOAD_DATE') . "  " . "⇩", + //7 => JText::_('COM_PHOCADOWNLOAD_ID') . "  " . "⇧", + //8 => JText::_('COM_PHOCADOWNLOAD_ID') . "  " . "⇩", + 11 => Text::_('COM_PHOCADOWNLOAD_FILENAME') . "  " . "⇧", + 12 => Text::_('COM_PHOCADOWNLOAD_FILENAME') . "  " . "⇩", + + 15 => Text::_('COM_PHOCADOWNLOAD_COUNT') . "  " . "⇧", + 16 => Text::_('COM_PHOCADOWNLOAD_COUNT') . "  " . "⇩", + 13 => Text::_('COM_PHOCADOWNLOAD_RATING') . "  " . "⇧", + 14 => Text::_('COM_PHOCADOWNLOAD_RATING') . "  " . "⇩", + 9 => Text::_('COM_PHOCADOWNLOAD_DOWNLOADS') . "  " . "⇧", + 10 => Text::_('COM_PHOCADOWNLOAD_DOWNLOADS') . "  " . "⇩"); + + } else { + + + $itemOrdering = array( + 1 => Text::_('COM_PHOCADOWNLOAD_ORDERING_ASC'), + 2 => Text::_('COM_PHOCADOWNLOAD_ORDERING_DESC'), + 3 => Text::_('COM_PHOCADOWNLOAD_TITLE_ASC'), + 4 => Text::_('COM_PHOCADOWNLOAD_TITLE_DESC'), + 5 => Text::_('COM_PHOCADOWNLOAD_DATE_ASC'), + 6 => Text::_('COM_PHOCADOWNLOAD_DATE_DESC'), + //7 => JText::_('COM_PHOCADOWNLOAD_ID_ASC'), + //8 => JText::_('COM_PHOCADOWNLOAD_ID_DESC'), + 11 => Text::_('COM_PHOCADOWNLOAD_FILENAME_ASC'), + 12 => Text::_('COM_PHOCADOWNLOAD_FILENAME_DESC'), + + 15 => Text::_('COM_PHOCADOWNLOAD_RATING_COUNT_ASC'), + 16 => Text::_('COM_PHOCADOWNLOAD_RATING_COUNT_DESC'), + 13 => Text::_('COM_PHOCADOWNLOAD_AVERAGE_ASC'), + 14 => Text::_('COM_PHOCADOWNLOAD_AVERAGE_DESC'), + 9 => Text::_('COM_PHOCADOWNLOAD_DOWNLOADS_ASC'), + 10 => Text::_('COM_PHOCADOWNLOAD_DOWNLOADS_DESC')); + } + + $itemOrderingValuesA = explode(',', $item_ordering_values); + + //$itemOrdering = array_intersect_key($itemOrdering, $itemOrderingValues); + $validItemOrdering = array(); + foreach ($itemOrderingValuesA as $k => $v) { + if (isset($itemOrdering[$v])) { + $validItemOrdering[$v] = $itemOrdering[$v]; + } + } + + return $validItemOrdering; + } + + + + public static function getOrderingCategoryArray() { + $imgOrdering = array( + 1 => Text::_('COM_PHOCADOWNLOAD_ORDERING_ASC'), + 2 => Text::_('COM_PHOCADOWNLOAD_ORDERING_DESC'), + 3 => Text::_('COM_PHOCADOWNLOAD_TITLE_ASC'), + 4 => Text::_('COM_PHOCADOWNLOAD_TITLE_DESC'), + 5 => Text::_('COM_PHOCADOWNLOAD_DATE_ASC'), + 6 => Text::_('COM_PHOCADOWNLOAD_DATE_DESC'), + //7 => JText::_('COM_PHOCADOWNLOAD_ID_ASC'), + //8 => JText::_('COM_PHOCADOWNLOAD_ID_DESC'), + 11 => Text::_('COM_PHOCADOWNLOAD_RATING_COUNT_ASC'), + 12 => Text::_('COM_PHOCADOWNLOAD_RATING_COUNT_DESC'), + 13 => Text::_('COM_PHOCADOWNLOAD_AVERAGE_ASC'), + 14 => Text::_('COM_PHOCADOWNLOAD_AVERAGE_DESC'), + 15 => Text::_('COM_PHOCADOWNLOAD_HITS_ASC'), + 16 => Text::_('COM_PHOCADOWNLOAD_HITS_DESC')); + return $imgOrdering; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/pagination/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/pagination/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/pagination/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/pagination/pagination.php b/administrator/components/com_phocadownload/libraries/phocadownload/pagination/pagination.php new file mode 100644 index 00000000..030a241d --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/pagination/pagination.php @@ -0,0 +1,45 @@ +get( 'pagination', '5,10,15,20,50,100' ); + $paginationArray = explode( ',', $pagination ); + + // Initialize variables + $limits = array (); + + foreach ($paginationArray as $paginationValue) { + $limits[] = HTMLHelper::_('select.option', $paginationValue); + } + $limits[] = HTMLHelper::_('select.option', '0', Text::_('COM_PHOCADOWNLOAD_ALL')); + + $selected = $this->viewall ? 0 : $this->limit; + + // Build the select list + if ($app->isClient('administrator')) { + $html = HTMLHelper::_('select.genericlist', $limits, 'limit', 'class="form-select" size="1" onchange="submitform();"', 'value', 'text', $selected); + } else { + $html = HTMLHelper::_('select.genericlist', $limits, 'limit', 'class="form-select input-mini" size="1" onchange="this.form.submit()"', 'value', 'text', $selected); + } + return $html; + } + +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/path/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/path/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/path/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/path/path.php b/administrator/components/com_phocadownload/libraries/phocadownload/path/path.php new file mode 100644 index 00000000..d1a74bb0 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/path/path.php @@ -0,0 +1,90 @@ +get( 'download_folder', 'phocadownload' ); + $downloadFolderPap = $paramsC->get( 'download_folder_pap', 'phocadownloadpap' ); + // Absolute path which can be outside public_html - if this will be set, download folder will be ignored + $absolutePath = $paramsC->get( 'absolute_path', '' ); + + // Path of preview and play + $downloadFolderPap = Path::clean($downloadFolderPap); + $path['orig_abs_pap'] = JPATH_ROOT . '/' . $downloadFolderPap; + $path['orig_abs_pap_ds'] = $path['orig_abs_pap'] . '/' ; + + if ($group['f'] == 2) { + // Images + $path['orig_abs'] = JPATH_ROOT . '/' . 'images/phocadownload' ; + $path['orig_abs_ds'] = $path['orig_abs'] . '/' ; + $path['orig_abs_user_upload'] = $path['orig_abs'] . '/' . 'userupload' ; + $path['orig_abs_user_upload_pap']= $path['orig_abs_pap'] . '/' . 'userupload' ; + $path['orig_rel_ds'] = '../images/phocadownload/'; + } else if ($group['f'] == 3) { + // Play and Preview + $path['orig_abs'] = $path['orig_abs_pap']; + $path['orig_abs_ds'] = $path['orig_abs_pap_ds']; + $path['orig_abs_user_upload'] = $path['orig_abs'] . '/' . 'userupload' ; + $path['orig_abs_user_upload_pap']= $path['orig_abs_pap'] . '/' . 'userupload' ; + $path['orig_rel_ds'] = '../'.str_replace('\\', '/', Path::clean($downloadFolderPap)).'/'; + } else { + // Standard Path + if ($absolutePath != '') { + $downloadFolder = str_replace('\\', '/', Path::clean($absolutePath)); + $path['orig_abs'] = str_replace('\\', '/', Path::clean($absolutePath)); + $path['orig_abs_ds'] = Path::clean($path['orig_abs'] . '/') ; + $path['orig_abs_user_upload'] = Path::clean($path['orig_abs'] . '/' . 'userupload') ; + $path['orig_abs_user_upload_pap']= Path::clean($path['orig_abs_pap'] . '/' . 'userupload') ; + //$downloadFolderRel = str_replace('\\', '/', JPath::clean($downloadFolder)); + $path['orig_rel_ds'] = ''; + + } else { + $downloadFolder = str_replace('\\', '/', Path::clean($downloadFolder)); + $path['orig_abs'] = JPATH_ROOT . '/' . $downloadFolder ; + $path['orig_abs_ds'] = JPATH_ROOT . '/' . $downloadFolder . '/' ; + $path['orig_abs_user_upload'] = $path['orig_abs'] . '/' . 'userupload' ; + $path['orig_abs_user_upload_pap']= $path['orig_abs_pap'] . '/' . 'userupload' ; + + $downloadFolderRel = str_replace('\\', '/', Path::clean($downloadFolder)); + $path['orig_rel_ds'] = '../' . $downloadFolderRel .'/'; + } + } + return $path; + } + + public static function getPathMedia() { + + $option = 'com_phocadownload'; + $instance = new StdClass(); + $baseFront = Uri::root(true); + $instance->media_css_abs = JPATH_ROOT . '/' . 'media'. '/' . $option . '/' . 'css' . '/'; + $instance->media_img_abs = JPATH_ROOT . '/' . 'media'. '/' . $option . '/' . 'images' . '/'; + $instance->media_js_abs = JPATH_ROOT . '/' . 'media'. '/' . $option . '/' . 'js' . '/'; + $instance->media_css_rel = 'media/'. $option .'/css/'; + $instance->media_img_rel = 'media/'. $option .'/images/'; + $instance->media_js_rel = 'media/'. $option .'/js/'; + $instance->media_css_rel_full = $baseFront . '/' . $instance->media_css_rel; + $instance->media_img_rel_full = $baseFront . '/' . $instance->media_img_rel; + $instance->media_js_rel_full = $baseFront . '/' . $instance->media_js_rel; + return $instance; + + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/path/route.php b/administrator/components/com_phocadownload/libraries/phocadownload/path/route.php new file mode 100644 index 00000000..bf2a47ac --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/path/route.php @@ -0,0 +1,350 @@ + '' + ); + + $link = 'index.php?option=com_phocadownload&view=categories'; + + if($item = self::_findItem($needles, 1)) { + if(isset($item->query['layout'])) { + $link .= '&layout='.$item->query['layout']; + } + if (isset($item->id)) { + $link .= '&Itemid='.(int)$item->id;; + } + } + return $link; + } + + public static function getCategoryRoute($catid, $catidAlias = '') { + + $needles = array( + 'category' => (int)$catid, + 'categories' => '' + ); + + if ($catidAlias != '') { + $catid = $catid . ':' . $catidAlias; + } + + //Create the link + $link = 'index.php?option=com_phocadownload&view=category&id='. $catid; + + if($item = self::_findItem($needles)) { + if(isset($item->query['layout'])) { + $link .= '&layout='.$item->query['layout']; + } + if(isset($item->id)) { + $link .= '&Itemid='.$item->id; + } + }; + + return $link; + } + + public static function getCategoryRouteByTag($tagId) + { + $needles = array( + 'category' => '', + //'section' => (int) $sectionid, + 'categories' => '' + ); + + $db = Factory::getDBO(); + + $query = 'SELECT a.id, a.title, a.link_ext, a.link_cat' + .' FROM #__phocadownload_tags AS a' + .' WHERE a.id = '.(int)$tagId; + + $db->setQuery($query, 0, 1); + $tag = $db->loadObject(); + + /*if (!$db->query()) { + throw new Exception($db->getErrorMsg(), 500); + return false; + }*/ + + //Create the link + if (isset($tag->id)) { + $link = 'index.php?option=com_phocadownload&view=category&id=0:category&tagid='.(int)$tag->id; + } else { + $link = 'index.php?option=com_phocadownload&view=category&id=0:category&tagid=0'; + } + + if($item = self::_findItem($needles)) { + if(isset($item->query['layout'])) { + $link .= '&layout='.$item->query['layout']; + } + if(isset($item->id)) { + $link .= '&Itemid='.$item->id; + } + }; + + return $link; + } + + + public static function getFileRoute($id, $catid = 0, $idAlias = '', $catidAlias = '', $sectionid = 0, $type = 'file', $suffix = '') + { + + $needles = array( + 'file' => (int) $id, + 'category' => (int) $catid, + 'categories' => '' + ); + + if ($idAlias != '') { + $id = $id . ':' . $idAlias; + } + if ($catidAlias != '') { + $catid = $catid . ':' . $catidAlias; + } + + //Create the link + switch ($type) + { + + + case 'play': + $link = 'index.php?option=com_phocadownload&view=play&catid='.$catid.'&id='. $id.'&tmpl=component'; + break; + case 'detail': + $link = 'index.php?option=com_phocadownload&view=file&catid='.$catid.'&id='. $id.'&tmpl=component'; + break; + case 'download': + $link = 'index.php?option=com_phocadownload&view=category&download='. $id . '&id='. $catid; + break; + default: + $link = 'index.php?option=com_phocadownload&view=file&catid='.$catid.'&id='. $id; + break; + + } + + if ($item = self::_findItem($needles)) { + if (isset($item->id) && ((int)$item->id > 0)) { + $link .= '&Itemid='.$item->id; + } + } + + if ($suffix != '') { + $link .= '&'.$suffix; + } + + + return $link; + + + } + + public static function getDownloadRoute($id, $catid, $token, $directDownload = 1) + { + $needles = array( + 'download' => '', + 'file' => (int) $id, + 'category' => (int) $catid, + 'categories' => '' + ); + + if ($directDownload == 1) { + $link = 'index.php?option=com_phocadownload&view=download&id='. $token.'&download=1&' . Session::getFormToken() . '=1'; + } else { + $link = 'index.php?option=com_phocadownload&view=download&id='. $token; + } + + if($item = self::_findItem($needles)) { + if (isset($item->id)) { + $link .= '&Itemid='.$item->id; + } + } + + if ($item = PhocaDownloadRoute::_findItem($needles, 0)) { + if (isset($item->id) && ((int)$item->id > 0)) { + $link .= '&Itemid='.$item->id; + } + } + + return $link; + } + + public static function getFeedRoute($id, $catid = 0, $sectionid = 0, $type = 'rss') + { + $needles = array( + 'categories' => '', + 'category' => (int) $catid, + 'feed' => $id //feed + //'section' => (int) $sectionid, + //'category' => (int) $catid /*, + //'file' => (int) $id*/ + ); + + //Create the link + $link = 'index.php?option=com_phocadownload&view=feed&id='.$id.'&format=feed&type='.$type; + + if($item = self::_findItem($needles, 1)) { + if (isset($item->id)) { + $link .= '&Itemid='.$item->id; + } + } + return $link; + } + + public static function getGuestbookRoute($id, $title) + { + $needles = array( + 'guestbook' => (int) $id + ); + + $link = 'index.php?option=com_phocaguestbook&view=guestbook&cid='.(int)$id.'&reporttitle='.strip_tags($title).'&tmpl=component'; + + if($item = self::_findItem($needles, 1, 'com_phocaguestbook')) { + if (isset($item->id)) { + $link .= '&Itemid='.$item->id; + } + } + return $link; + } + + /* + function getSectionRoute($sectionid, $sectionidAlias = '') + { + $needles = array( + 'section' => (int) $sectionid, + 'sections' => '' + ); + + if ($sectionidAlias != '') { + $sectionid = $sectionid . ':' . $sectionidAlias; + } + + //Create the link + $link = 'index.php?option=com_phocadownload&view=section&id='.$sectionid; + + if($item = self::_findItem($needles)) { + if(isset($item->query['layout'])) { + $link .= '&layout='.$item->query['layout']; + } + $link .= '&Itemid='.$item->id; + } + + return $link; + } + + function getSectionsRoute() + { + $needles = array( + 'sections' => '' + ); + + //Create the link + $link = 'index.php?option=com_phocadownload&view=sections'; + + if($item = self::_findItem($needles)) { + if(isset($item->query['layout'])) { + $link .= '&layout='.$item->query['layout']; + } + if (isset($item->id)) { + $link .= '&Itemid='.$item->id; + } + } + + return $link; + }*/ + + protected static function _findItem($needles, $notCheckId = 0, $component = 'com_phocadownload') + { + + $app = Factory::getApplication(); + //$menus = $app->getMenu('site', array()); // Problems in indexer + $menus = AbstractMenu::getInstance('site'); + $items = $menus->getItems('component', $component); + //$menu = $menus;//$app->getMenu(); + $active = $menus->getActive(); + $option = $app->input->get( 'option', '', 'string' ); + + // Don't check ID for specific views. e.g. categories view does not have ID + $notCheckIdArray = array('categories'); + + if(!$items) { + $itemId = $app->input->get('Itemid', 0, 'int'); + if ($itemId > 0) { + $item = new stdClass(); + $item->id = $itemId; + return $item; + } + return null; + } + + $match = null; + // FIRST - test active menu link + foreach($needles as $needle => $id) { + if (isset($active->query['option']) && $active->query['option'] == $component + && isset($active->query['view']) && $active->query['view'] == $needle + && (in_array($needle, $notCheckIdArray) || (isset($active->query['id']) && $active->query['id'] == $id )) + ) { + $match = $active; + } + } + + if(isset($match)) { + return $match; + } + + // SECOND - if not find in active, try to run other items + // ordered by function which calls this function - e.g. file, category, categories + // as last the categories view should be checked, it has no ID so we skip the checking + // of ID for categories view with OR: in_array($needle, $notCheckIdArray) || + foreach($needles as $needle => $id) { + + foreach($items as $item) { + + if (isset($item->query['option']) && $item->query['option'] == $component + && isset($item->query['view']) && $item->query['view'] == $needle + && (in_array($needle, $notCheckIdArray) || (isset($item->query['id']) && $item->query['id'] == $id )) + ) { + $match = $item; + } + } + + if(isset($match)) { + break; + } + } + + return $match; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/path/routerrules.php b/administrator/components/com_phocadownload/libraries/phocadownload/path/routerrules.php new file mode 100644 index 00000000..908f416c --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/path/routerrules.php @@ -0,0 +1,209 @@ +input->get('tagid', 0, 'int'); + if ($segments[0] == 'category' && (int)$tagId > 0){ + // We are in category view but tags output + $vars['view'] = 'category'; + unset($segments[0]); + } + + // SPECIFIC CASE FEED (we prevent the word "feed" in URL) + $format = $app->input->get('format', '', 'string'); + if ($format == 'feed') { + if ($segments[0] == 'feed'){ + + $vars['view'] = 'feed'; + if (isset($segments[1]) && (int)($segments[1] > 0)) { + $vars['id'] = (int)$segments[1]; + unset($segments[1]); + } + unset($segments[0]); + } + } + + + return parent::parse($segments, $vars); + } + + /* EDIT of libraries/src/Component/Router/Rules/StandardRules.php build function + * Because we need to manage when categories view does not have any ID + * PHOCAEDIT + */ + public function build(&$query, &$segments) { + + + + if (!isset($query['Itemid'], $query['view'])) { + return; + } + + // Get the menu item belonging to the Itemid that has been found + $item = $this->router->menu->getItem($query['Itemid']); + + if ($item === null || $item->component !== 'com_' . $this->router->getName() || !isset($item->query['view'])) { + return; + } + + // PHOCAEDIT + if (!isset($item->query['id']) ){ + $item->query['id'] = 0; + } + + // Get menu item layout + $mLayout = isset($item->query['layout']) ? $item->query['layout'] : null; + + // Get all views for this component + $views = $this->router->getViews(); + + + // Return directly when the URL of the Itemid is identical with the URL to build + if ($item->query['view'] === $query['view']) { + $view = $views[$query['view']]; + + if (!$view->key) { + ///unset($query['view']); + + if (isset($query['layout']) && $mLayout === $query['layout']) { + unset($query['layout']); + } + + return; + } + + if (isset($query[$view->key]) && $item->query[$view->key] == (int) $query[$view->key]) { + ///unset($query[$view->key]); + + while ($view) { + ///unset($query[$view->parent_key]); + + $view = $view->parent; + } + + + /// unset($query['view']); + + + if (isset($query['layout']) && $mLayout === $query['layout']) { + unset($query['layout']); + } + + return; + } + } + + // Get the path from the view of the current URL and parse it to the menu item + $path = array_reverse($this->router->getPath($query), true); + $found = false; + + foreach ($path as $element => $ids) { + $view = $views[$element]; + + if ($found === false && $item->query['view'] === $element) { + if ($view->nestable) { + $found = true; + } elseif ($view->children) { + $found = true; + + continue; + } + } + + if ($found === false) { + // Jump to the next view + continue; + } + + if ($ids) { + + if ($view->nestable) { + $found2 = false; + + foreach (array_reverse($ids, true) as $id => $segment) { + + if ($found2) { + $segments[] = str_replace(':', '-', $segment); + + } elseif ((int) $item->query[$view->key] === (int) $id) { + $found2 = true; + + // SPECIFIC CASE TAG - tag search output in category view + // 1. components/com_phocadownload/router.php getCategorySegment() - BUILD + // 2. administrator/components/com_phocadownload/libraries/phocadownload/path/routerrules.php build() - BUILD + // 3. administrator/components/com_phocadownload/libraries/phocadownload/path/routerrules.php parse() - PARSE + if ((int)$query['id'] == 0 && $query['view'] == 'category' && isset($query['tagid']) && (int)$query['tagid'] > 0) { + $segments[] = 'category'; + } + } + } + } elseif ($ids === true) { + + $segments[] = $element; + } else { + + // FEED + // Specific case: feed view (we just use the "feed" in url + if (isset($query['view']) && $query['view'] == 'feed') { + // /feed/number_of_module_id + $segments[] = 'feed'; + $segments[] = str_replace(':', '-', current($ids)); + } else { + $segments[] = str_replace(':', '-', current($ids)); + } + + } + } + + if ($view->parent_key) { + // Remove parent key from query + unset($query[$view->parent_key]); + } + } + + if ($found) { + unset($query[$views[$query['view']]->key], $query['view']); + + if (isset($query['layout']) && $mLayout === $query['layout']) { + unset($query['layout']); + } + } + + + + /* if ($query['format'] == 'feed') { + + $segments['view'] = 'feed'; + }*/ + + } +} diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/rate/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/rate/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/rate/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/rate/rate.php b/administrator/components/com_phocadownload/libraries/phocadownload/rate/rate.php new file mode 100644 index 00000000..efc8dad9 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/rate/rate.php @@ -0,0 +1,302 @@ +setQuery($query, 0, 1); + $votesStatistics = $db->loadObject(); + // if no count, set the average to 0 + if($votesStatistics->count == 0) { + $votesStatistics->count = (int)0; + $votesStatistics->average = (float)0; + } + + if (isset($votesStatistics->count) && isset($votesStatistics->average)) { + // Insert or update + $query = 'SELECT vs.id AS id' + .' FROM #__phocadownload_file_votes_statistics AS vs' + .' WHERE vs.fileid = '.(int) $fileid + .' ORDER BY vs.id'; + $db->setQuery($query, 0, 1); + $votesStatisticsId = $db->loadObject(); + + // Yes, there is id (UPDATE) x No, there isn't (INSERT) + if (!empty($votesStatisticsId->id)) { + + $query = 'UPDATE #__phocadownload_file_votes_statistics' + .' SET count = ' .(int)$votesStatistics->count + .' , average = ' .(float)$votesStatistics->average + .' WHERE fileid = '.(int) $fileid; + $db->setQuery($query); + + if (!$db->execute()) { + + throw new Exception('Database Error Voting 1', 500); + return false; + } + + } else { + + $query = 'INSERT into #__phocadownload_file_votes_statistics' + .' (id, fileid, count, average)' + .' VALUES (null, '.(int)$fileid + .' , '.(int)$votesStatistics->count + .' , '.(float)$votesStatistics->average + .')'; + $db->setQuery($query); + + if (!$db->execute()) { + + throw new Exception('Database Error Voting 2', 500); + return false; + } + + } + } else { + return false; + } + return true; + } + + public static function getVotesStatisticsFile($id) { + + $db = Factory::getDBO(); + $query = 'SELECT vs.count AS count, vs.average AS average' + .' FROM #__phocadownload_file_votes_statistics AS vs' + .' WHERE vs.fileid = '.(int) $id + .' ORDER BY vs.fileid'; + $db->setQuery($query, 0, 1); + $votesStatistics = $db->loadObject(); + + return $votesStatistics; + } + + public static function checkUserVoteFile($fileid, $userid) { + + $db = Factory::getDBO(); + $query = 'SELECT v.id AS id' + .' FROM #__phocadownload_file_votes AS v' + .' WHERE v.fileid = '. (int)$fileid + .' AND v.userid = '. (int)$userid + .' ORDER BY v.id'; + $db->setQuery($query, 0, 1); + $checkUserVote = $db->loadObject(); + if ($checkUserVote) { + return true; + } + return false; + } + + + public static function renderRateFile($id, $displayRating, $small = 1, $refresh = false) { + + $user = Factory::getUser(); + $neededAccessLevels = PhocaDownloadAccess::getNeededAccessLevels(); + $access = PhocaDownloadAccess::isAccess($user->getAuthorisedViewLevels(), $neededAccessLevels); + + + if ($small == 1) { + $smallO = '-small'; + $ratio = 18; + } else { + $smallO = ''; + $ratio = 22; + } + + $o = ''; + + //.$rating['urlvote'].$amp.'controller=detail&task=rate&rating=1 + //$amp = PhocaDownloadAccess::setQuestionmarkOrAmp($rating['urlvote']); + $href = 'javascript:void(0);'; + + if ((int)$displayRating != 1) { + return ''; + } else { + + $rating['alreadyratedfile'] = self::checkUserVoteFile( (int)$id, (int)$user->id ); + + $rating['notregisteredfile'] = true; + //$rating['usernamefile'] = ''; + if ($access > 0) { + $rating['notregisteredfile'] = false; + $rating['usernamefile'] = $user->name; + } + + $rating['votescountfile'] = 0; + $rating['votesaveragefile'] = 0; + $rating['voteswidthfile'] = 0; + $votesStatistics = self::getVotesStatisticsFile((int)$id); + if (!empty($votesStatistics->count)) { + $rating['votescountfile'] = $votesStatistics->count; + } + if (!empty($votesStatistics->average)) { + $rating['votesaveragefile'] = $votesStatistics->average; + if ($rating['votesaveragefile'] > 0) { + $rating['votesaveragefile'] = round(((float)$rating['votesaveragefile'] / 0.5)) * 0.5; + $rating['voteswidthfile'] = $ratio * $rating['votesaveragefile']; + } else { + $rating['votesaveragefile'] = (int)0;// not float displaying + } + } + + // Leave message for already voted images + //$vote = JFactory::getApplication()->input->get('vote', 0, '', 'int'); + $voteMsg = Text::_('COM_PHOCADOWNLOAD_RATING_ALREADY_RATED_FILE'); + //if ($vote == 1) { + // $voteMsg = JText::_('COM_PHOCADOWNLOAD_ALREADY_RATED_FILE_THANKS'); + //} + + $rating['votestextimg'] = 'VOTE'; + if ((int)$rating['votescountfile'] > 1) { + $rating['votestextimg'] = 'VOTES'; + } + + + $o .= '
' + . Text::_('COM_PHOCADOWNLOAD_RATING'). ': ' . $rating['votesaveragefile'] .' / ' + .$rating['votescountfile'] . ' ' . Text::_('COM_PHOCADOWNLOAD_'.$rating['votestextimg']). '  
'; + + if ($rating['alreadyratedfile']) { + $o .= '
    ' + .'
  • ' + .'
  • '; + + for ($i = 2;$i < 6;$i++) { + $o .= '
  • '; + } + $o .= '
'; + + $or ='
'.Text::_('COM_PHOCADOWNLOAD_RATING_ALREADY_RATED_FILE').'
'; + + } else if ($rating['notregisteredfile']) { + + $o .= '
    ' + .'
  • ' + .'
  • '; + + for ($i = 2;$i < 6;$i++) { + $o .= '
  • '; + } + $o .= '
'; + + $or ='
'.Text::_('COM_PHOCADOWNLOAD_ONLY_REGISTERED_LOGGED_RATE_FILE').'
'; + + } else { + + $o .= '
    ' + .'
  • ' + .'
  • 1
  • '; + + for ($i = 2;$i < 6;$i++) { + $o .= '
  • '.$i.'
  • '; + } + $o .= '
'; + + $or ='
'; + } + + + + } + + if ($refresh == true) { + return $o;//we are in Ajax, return only content of pdvoting div + } else { + return '
'.$o.'
' .$or ;//not in ajax, return the contend in div + } + + + } + + public static function renderRateFileJS($small = 1) { + + $document = Factory::getDocument(); + $url = 'index.php?option=com_phocadownload&view=ratingfilea&task=rate&format=json&'.Session::getFormToken().'=1'; + $urlRefresh = 'index.php?option=com_phocadownload&view=ratingfilea&task=refreshrate&small='.$small.'&format=json&'.Session::getFormToken().'=1'; + $imgLoadingUrl = Uri::base(). 'media/com_phocadownload/images/icon-loading2.gif'; + $imgLoadingHTML = ''; + + + $url = Route::_($url, false); + $urlRefresh = Route::_($urlRefresh, false); + + + $js = ''; + $document->addCustomTag($js); + + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/render/layout.php b/administrator/components/com_phocadownload/libraries/phocadownload/render/layout.php new file mode 100644 index 00000000..9c5847a6 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/render/layout.php @@ -0,0 +1,327 @@ +params = ComponentHelper::getParams('com_phocadownload') ; + } + + if ($this->filePath == '') { + $this->filePath = PhocaDownloadPath::getPathSet('file'); + } + + if ($this->iconPath == '') { + $this->iconPath = PhocaDownloadPath::getPathSet('icon'); + } + + if ($this->cssImagePath == '') { + $this->cssImagePath = str_replace ( '../', Uri::base(true).'/', $this->iconPath['orig_rel_ds']); + } + + if ($this->fileAbsPath == '') { + $this->fileAbsPath = $this->filePath['orig_abs_ds']; + } + + } + + + public function getName($title, $filename, $preferTitle = 0) { + + $name = $title; + $fon = $this->params->get( 'filename_or_name', 'filename' ); + + if ($fon == 'title') { + $name = $title; + } else if ($fon == 'filename'){ + $name = PhocaDownloadFile::getTitleFromFilenameWithExt( $filename ); + } else if ($fon == 'filenametitle'){ + if ($preferTitle == 1) { + $name = $title; + } else { + // Must be solved before + $name = PhocaDownloadFile::getTitleFromFilenameWithExt( $filename ); + } + } + + return $name; + } + + public function getImageFileName($imageFilename, $fileName = '', $type = 1, $iconSize = 16) { + + $name['filenamestyle'] = ''; + $name['filenamethumb'] = ''; + + if ($imageFilename !='') { + $thumbnail = false; + $thumbnail = preg_match("/phocathumbnail/i", $imageFilename); + if ($thumbnail) { + $name['filenamethumb'] = '
' + .'
'; + $name['filenamestyle'] = ''; + } else { + $name['filenamethumb'] = ''; + $name['filenamestyle'] = 'style="background: url(\''.$this->cssImagePath.$imageFilename.'\') 0 center no-repeat;"'; + } + } else { + $file_icon_mime = $this->params->get( 'file_icon_mime', 1 ); + if ($fileName != '' && $file_icon_mime == 1) { + if ($type == 3) { // Plugin + $file_icon_size = $iconSize; + } else if ($type == 2) { + $file_icon_size = $this->params->get( 'file_icon_size_md', 16 ); + } else { + $file_icon_size = $this->params->get( 'file_icon_size', 16 ); + } + $icon = PhocaDownloadFile::getMimeTypeIcon($fileName, (int)$file_icon_size, 1); + $name['filenamethumb'] = ''; + $name['filenamestyle'] = $icon; + } + } + + + return $name; + } + + public function getFileSize($filename) { + + $size = ''; + if ($filename != '') { + $absFile = str_replace('\\', '/', Path::clean($this->fileAbsPath . $filename)); + if (File::exists($absFile)) { + $size = PhocaDownloadFile::getFileSizeReadable(filesize($absFile)); + } else { + $size = ''; + } + } + + return $size; + } + + public function getProtectEmail($email) { + + $email = str_replace('@', '['.Text::_('COM_PHOCADOWNLOAD_AT').']', $email); + $email = str_replace('.', '['.Text::_('COM_PHOCADOWNLOAD_DOT').']', $email); + + return $email; + } + + public function getFileDate($filename, $date) { + + $dateO = ''; + $ddt = $this->params->get( 'display_date_type', 0 ); + if ((int)$ddt > 0) { + if ($filename !='') { + $dateO = PhocaDownloadFile::getFileTime($filename, $ddt); + } + } else { + $dateO = HTMLHelper::Date($date, Text::_('DATE_FORMAT_LC3')); + } + + return $dateO; + } + + public function isValueEditor($text) { + + if ($text != '' && $text != '

 

' && $text != '

 

' && $text != '

' && $text != '
') { + return true; + } + return false; + } + + public function getImageDownload($img) { + + return ''; + } + + public function displayTags($fileId, $type = 0) { + + $o = ''; + $db = Factory::getDBO(); + + $query = 'SELECT a.id, a.title, a.link_ext, a.link_cat' + .' FROM #__phocadownload_tags AS a' + .' LEFT JOIN #__phocadownload_tags_ref AS r ON r.tagid = a.id' + .' WHERE r.fileid = '.(int)$fileId + .' ORDER BY a.id'; + + $db->setQuery($query); + + try { + $fileIdObject = $db->loadObjectList(); + } catch (\Exception $e) { + throw new \Exception($e->getMessage(), 500); + } + + $tl = $this->params->get( 'tags_links', 0 ); + + $class = ''; + if ($type == 1) { + $class = 'class="label label-default"'; + } + + foreach ($fileIdObject as $k => $v) { + $o .= ''; + if ($tl == 0) { + $o .= $v->title; + } else if ($tl == 1) { + if ($v->link_ext != '') { + $o .= ''.$v->title.''; + } else { + $o .= $v->title; + } + } else if ($tl == 2) { + + if ($v->link_cat != '') { + $query = 'SELECT a.id, a.alias' + .' FROM #__phocadownload_categories AS a' + .' WHERE a.id = '.(int)$v->link_cat + .' ORDER BY a.id'; + + $db->setQuery($query, 0, 1); + + + try { + $category = $db->loadObject(); + } catch (\RuntimeException $e) { + throw new \Exception($e->getMessage(), 500); + } + + if (isset($category->id) && isset($category->alias)) { + $link = PhocaDownloadRoute::getCategoryRoute($category->id, $category->alias); + $o .= ''.$v->title.''; + } else { + $o .= $v->title; + } + } else { + $o .= $v->title; + } + } else if ($tl == 3) { + $link = PhocaDownloadRoute::getCategoryRouteByTag($v->id); + $o .= ''.$v->title.''; + } + + $o .= ' '; + } + + return $o; + } + + public function displayTagsString($string = '') { + $o = array(); + if ($string != '') { + $sA = explode(',', $string); + if (!empty($sA)) { + foreach ($sA as $k => $v) { + // Specific cases for Joomla! CMS + switch($v) { + case '1.5': $c = 'pd-j-15'; break; + case '1.7': $c = 'pd-j-17'; break; + case '2.5': $c = 'pd-j-25'; break; + case '3.x': $c = 'pd-j-3x'; break; + case '3.5': $c = 'pd-j-35'; break; + case '4.x': $c = 'pd-j-4x'; break; + case '4.0': $c = 'pd-j-40'; break; + default: $c = 'label-default bg-default label-'. PhocaDownloadUtils::getAliasName($v);break; + } + + $o[] = ''.trim($v).''; + } + } + } + return implode(" ", $o); + + } + + + public function displayVideo($url, $view = 0, $ywidth = 0, $yheight = 0) { + + $o = ''; + + $app = Factory::getApplication(); + + + if ($view == 0) { + // Category View + $height = $this->params->get( 'youtube_height_cv', 240 ); + $width = $this->params->get( 'youtube_width_cv', 320 ); + } else { + // Detail View + $height = $this->params->get( 'youtube_height_dv', 360 ); + $width = $this->params->get( 'youtube_width_dv', 480 ); + } + + if ($url != '' && PhocaDownloadUtils::isURLAddress($url) ) { + + + $ssl = strpos($url, 'https'); + $yLink = 'http://www.youtube.com/v/'; + if ($ssl != false) { + $yLink = 'https://www.youtube.com/v/'; + } + + $shortUrl = 'http://youtu.be/'; + $shortUrl2 = 'https://youtu.be/'; + $pos = strpos($url, $shortUrl); + $pos2 = strpos($url, $shortUrl2); + if ($pos !== false) { + $code = str_replace($shortUrl, '', $url); + } else if ($pos2 !== false) { + $code = str_replace($shortUrl2, '', $url); + } else { + $codeArray = explode('=', $url); + $code = str_replace($codeArray[0].'=', '', $url); + } + + + + if ((int)$ywidth > 0) { + $width = (int)$ywidth; + } + if ((int)$yheight > 0) { + $height = (int)$yheight; + } + + $attr = ''; + if ((int)$width > 0) { + $attr .= ' width="'.(int)$width.'"'; + } + if ((int)$height > 0) { + $attr .= ' height="'.(int)$height.'"'; + } + + $o .= '
'; + $o .= ''; + $o .= '
'; + /*$o .= '' + .'' + .'' + .'' + .'';*/ + } + return $o; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadmin.php b/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadmin.php new file mode 100644 index 00000000..292d92cd --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadmin.php @@ -0,0 +1,108 @@ +' + .'' + .HTMLHelper::_('image', $imgUrl . $image, $text ) + .'
'.$text.'
'. "\n"; + } + + public static function getLinks() { + $app = Factory::getApplication(); + $option = $app->input->get('option'); + $oT = strtoupper($option); + + $links = array(); + switch ($option) { + + case 'com_phocadownload': + $links[] = array('Phoca Download site', 'https://www.phoca.cz/phocadownload'); + $links[] = array('Phoca Download documentation site', 'https://www.phoca.cz/documentation/category/17-phoca-download-component'); + $links[] = array('Phoca Download download site', 'https://www.phoca.cz/download/category/68-phoca-download'); + break; + + } + + $links[] = array('Phoca News', 'https://www.phoca.cz/news'); + $links[] = array('Phoca Forum', 'https://www.phoca.cz/forum'); + + $components = array(); + $components[] = array('Phoca Gallery','phocagallery', 'pg'); + $components[] = array('Phoca Guestbook','phocaguestbook', 'pgb'); + $components[] = array('Phoca Download','phocadownload', 'pd'); + $components[] = array('Phoca Documentation','phocadocumentation', 'pdc'); + $components[] = array('Phoca Favicon','phocafavicon', 'pfv'); + $components[] = array('Phoca SEF','phocasef', 'psef'); + $components[] = array('Phoca PDF','phocapdf', 'ppdf'); + $components[] = array('Phoca Restaurant Menu','phocamenu', 'prm'); + $components[] = array('Phoca Maps','phocamaps', 'pm'); + $components[] = array('Phoca Font','phocafont', 'pf'); + $components[] = array('Phoca Email','phocaemail', 'pe'); + $components[] = array('Phoca Install','phocainstall', 'pi'); + $components[] = array('Phoca Template','phocatemplate', 'pt'); + $components[] = array('Phoca Panorama','phocapanorama', 'pp'); + $components[] = array('Phoca Photo','phocaphoto', 'ph'); + $components[] = array('Phoca Commander','phocacommander', 'pcm'); + + $banners = array(); + $banners[] = array('Phoca Restaurant Menu','phocamenu', 'prm'); + $banners[] = array('Phoca Cart','phocacart', 'pc'); + + $o = ''; + $o .= '

 

'; + $o .= '

'. Text::_($oT.'_USEFUL_LINKS'). '

'; + $o .= ''; + + $o .= '
'; + $o .= '

 

'; + $o .= '

'. Text::_($oT.'_USEFUL_TIPS'). '

'; + + $m = mt_rand(0, 10); + if ((int)$m > 0) { + $o .= '
'; + $num = range(0,(count($components) - 1 )); + shuffle($num); + for ($i = 0; $i<3; $i++) { + $numO = $num[$i]; + $o .= '
'; + $o .= ''; + $o .= ''; + $o .= '
'; + } + $o .= '
'; + $o .= '
'; + } else { + $num = range(0,(count($banners) - 1 )); + shuffle($num); + $numO = $num[0]; + $o .= '
'. HTMLHelper::_('image', 'media/'.$option.'/images/administrator/b-'.$banners[$numO][2].'.png', ''). '
'; + + } + + $o .= '

 

'; + $o .= '

'. Text::_($oT.'_PLEASE_READ'). '

'; + $o .= '
'. Text::_($oT.'_PHOCA_NEEDS_YOUR_HELP'). '
'; + + $o .= '
'; + return $o; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadminview.php b/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadminview.php new file mode 100644 index 00000000..89564cd3 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadminview.php @@ -0,0 +1,37 @@ + diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadminviews.php b/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadminviews.php new file mode 100644 index 00000000..759d6937 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/render/renderadminviews.php @@ -0,0 +1,635 @@ +isCompatible('4.2.0-beta'); + + if ($is42) { + $this->document = Factory::getDocument(); + $wa = $this->document->getWebAssetManager(); + $wa->useScript('table.columns')->useScript('multiselect'); + } + + parent::__construct(); + } + +/* + public function startMainContainer() { + + $o = array(); + + if ($this->compatible) { + + // Joomla! 4 + + $o[] = '
'; + if ($this->sidebar) { + + $o[] = '
'; + } else { + + $o[] = '
'.JHtmlSidebar::render().'
'; + $o[] = '
'; + } + + + } else { + $o[] = '
'.JHtmlSidebar::render().'
'; + $o[] = '
'; + } + + return implode("\n", $o); + } + + public function endMainContainer() { + $o = array(); + + $o[] = '
'; + if ($this->compatible) { + $o[] = '
'; + } + return implode("\n", $o); + } + + + public function jsJorderTable($listOrder) { + + $js = 'Joomla.orderTable = function() {' . "\n" + .' table = document.getElementById("sortTable");' . "\n" + .' direction = document.getElementById("directionTable");' . "\n" + .' order = table.options[table.selectedIndex].value;' . "\n" + .' if (order != \''. $listOrder.'\') {' . "\n" + .' dirn = \'asc\';' . "\n" + .' } else {' . "\n" + .' dirn = direction.options[direction.selectedIndex].value;' . "\n" + .' }' . "\n" + .' Joomla.tableOrdering(order, dirn, \'\');' . "\n" + .'}' . "\n"; + Factory::getDocument()->addScriptDeclaration($js); + } + + public function startForm($option, $view, $id = 'adminForm', $name = 'adminForm') { + return '
'."\n"; + } + + public function endForm() { + return '
'."\n".'
'."\n"; + } + + public function selectFilterPublished($txtSp, $state) { + return '
'. "\n" + .'
'. "\n"; + } + + public function selectFilterActived($txtSp, $state) { + + + switch($state) { + case '0': + $aS = ''; + $nS = 'selected'; + $n = ''; + + break; + case '1': + $aS = 'selected'; + $nS = ''; + $n = ''; + break; + default: + $aS = ''; + $nS = ''; + $n = 'selected'; + break; + } + + return '
'. "\n" + .'
'. "\n"; + } + + public function selectFilterType($txtSp, $type, $typeList) { + return '
'. "\n" + .'
'. "\n"; + } + + public function selectFilterLanguage($txtLng, $state) { + return '
'. "\n" + .'
'. "\n"; + } + + public function selectFilterCategory($categoryList, $txtLng, $state) { + return '
'. "\n" + .'
'. "\n"; + } + + public function selectFilterLevels($txtLng, $state) { + $levelList = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5); + return + '
'. "\n" + .'
'. "\n"; + } + + public function inputFilterSearch($txtSl, $txtSd, $state) { + return ''. "\n"; + } + + /*public function inputFilterSearchClear($txtFs, $txtFc) { + return '
'. "\n" + .''. "\n" + .''. "\n" + .'
'. "\n"; + }*//* + + public function inputFilterSearchClear($txtFs, $txtFc) { + return '
'. "\n" + .''. "\n" + .''. "\n" + .'
'. "\n"; + } + + public function inputFilterSearchLimit($txtSl, $paginationLimitBox) { + return '
'. "\n" + .''. "\n" + .$paginationLimitBox ."\n" . '
'. "\n"; + } + + public function selectFilterDirection($txtOd, $txtOasc, $txtOdesc, $listDirn) { + $ascDir = $descDir = ''; + if ($listDirn == 'asc') {$ascDir = 'selected="selected"';} + if ($listDirn == 'desc') {$descDir = 'selected="selected"';} + return '
'. "\n" + .''. "\n" + .''. "\n" + .'
'. "\n"; + } + + public function selectFilterSortBy($txtSb, $sortFields, $listOrder) { + return '
'. "\n" + .''. "\n" + .''. "\n" + .'
'. "\n"; + } + + public function startTable($id) { + return ''. "\n"; + } + + public function endTable() { + return '
'. "\n"; + } + public function tblFoot($listFooter, $columns) { + return '' . "\n" . ''.$listFooter.''. "\n".''. "\n"; + } + + public function startTblHeader() { + return ''."\n".''."\n"; + } + + public function endTblHeader() { + return ''."\n".''."\n"; + } + + public function thOrdering($txtHo, $listDirn, $listOrder ) { + return ''. "\n" + . HTMLHelper::_('searchtools.sort', '', 'a.ordering', $listDirn, $listOrder, null, 'asc', $txtHo). "\n" + . ''; + } + + public function thOrderingXML($txtHo, $listDirn, $listOrder, $prefix = 'a', $empty = false ) { + + if ($empty) { + return ''. "\n"; + } + + return ''. "\n" + . HTMLHelper::_('searchtools.sort', '', strip_tags($prefix).'.ordering', $listDirn, $listOrder, null, 'asc', $txtHo, 'icon-menu-2'). "\n" + . ''; + //JHtml::_('searchtools.sort', $this->t['l'].'_IN_STOCK', 'a.stock', $listDirn, $listOrder ).''."\n"; + + } + + public function thCheck($txtCh) { + return ''. "\n" + .''. "\n" + .''. "\n"; + } + + public function tdOrder($canChange, $saveOrder, $orderkey, $ordering = 0){ + + $o = ''. "\n"; + if ($canChange) { + $disableClassName = ''; + $disabledLabel = ''; + if (!$saveOrder) { + $disabledLabel = Text::_('JORDERINGDISABLED'); + $disableClassName = 'inactive tip-top'; + } + $o .= ''."\n"; + } else { + $o .= ''."\n"; + } + $orderkeyPlus = $ordering;//$orderkey + 1; + $o .= ''. "\n" + .''. "\n"; + return $o; + } +/* + public function tdRating($ratingAvg) { + $o = ''; + $voteAvg = round(((float)$ratingAvg / 0.5)) * 0.5; + $voteAvgWidth = 16 * $voteAvg; + $o .= '
    ' + .'
  • ' + .'
  • '; + + for ($ir = 2;$ir < 6;$ir++) { + $o .= '
  • '; + } + $o .= '
'; + $o .=''. "\n"; + return $o; + } + + public function tdLanguage($lang, $langTitle, $langTitleE ) { + + $o = ''; + if ($lang == '*') { + $o .= Text::_('JALL'); + } else { + if ($langTitle) { + $o .= $langTitleE; + } else { + $o .= Text::_('JUNDEFINED');; + } + } + $o .= ''. "\n"; + return $o; + } + + /*public function formInputs($listOrder, $originalOrders) { + + return ''. "\n" + .''. "\n" + .''. "\n" + .''. "\n" + . HTMLHelper::_('form.token'). "\n" + .''. "\n"; + }*/ +/* + public function formInputs($listOrder, $listDirn, $originalOrders) { + + return ''. "\n" + .''. "\n" + .''. "\n" + .''. "\n" + . HTMLHelper::_('form.token'). "\n" + .''. "\n"; + } + + public function formInputsXml($listOrder, $listDirn, $originalOrders) { + + return ''. "\n" + .''. "\n" + //.''. "\n" + //.''. "\n" + . HTMLHelper::_('form.token'). "\n" + .''. "\n"; + } + + public function td($value, $class = '') { + if ($class != ''){ + return ''. $value.''. "\n"; + } else { + return ''. $value.''. "\n"; + } + } + + + + + public function tdPublishDownUp ($publishUp, $publishDown, $langPref) { + + $o = ''; + $db = Factory::getDBO(); + //$app = JFactory::getApplication(); + $nullDate = $db->getNullDate(); + $now = Factory::getDate(); + $config = Factory::getConfig(); + $publish_up = Factory::getDate($publishUp); + $publish_down = Factory::getDate($publishDown); + $tz = new DateTimeZone($config->get('offset')); + $publish_up->setTimezone($tz); + $publish_down->setTimezone($tz); + + + if ( $now->toUnix() <= $publish_up->toUnix() ) { + $text = Text::_( $langPref . '_PENDING' ); + } else if ( ( $now->toUnix() <= $publish_down->toUnix() || $publishDown == $nullDate ) ) { + $text = Text::_( $langPref . '_ACTIVE' ); + } else if ( $now->toUnix() > $publish_down->toUnix() ) { + $text = Text::_( $langPref . '_EXPIRED' ); + } + + $times = ''; + if (isset($publishUp)) { + if ($publishUp == $nullDate) { + $times .= "\n". Text::_( $langPref . '_START') . ': '.Text::_( $langPref . '_ALWAYS' ); + } else { + $times .= "\n". Text::_( $langPref . '_START') .": ". $publish_up->format("D, d M Y H:i:s"); + } + } + if (isset($publishDown)) { + if ($publishDown == $nullDate) { + $times .= "\n". Text::_( $langPref . '_FINISH'). ': '. Text::_( $langPref . '_NO_EXPIRY' ); + } else { + $times .= "\n". Text::_( $langPref . '_FINISH') .": ". $publish_down->format("D, d M Y H:i:s"); + } + } + + if ( $times ) { + $o .= '' + .'' + .''. $text.'' + .''. "\n"; + } else { + $o .= ''. "\n"; + } + return $o; + } + + public function saveOrder($t, $listDirn) { + + $saveOrderingUrl = 'index.php?option=' . $t['o'] . '&task=' . $t['tasks'] . '.saveOrderAjax&tmpl=component&' . Session::getFormToken() . '=1'; + if ($this->compatible) { + HTMLHelper::_('draggablelist.draggable'); + } else { + HTMLHelper::_('sortablelist.sortable', 'categoryList', 'adminForm', strtolower($listDirn), $saveOrderingUrl, false, true); + } + + return $saveOrderingUrl; + } + + public function firstColumnHeader($listDirn, $listOrder, $prefix = 'a', $empty = false) { + if ($this->compatible) { + // to do empty + return ''. HTMLHelper::_('grid.checkall').''; + } else { + return $this->thOrderingXML('JGRID_HEADING_ORDERING', $listDirn, $listOrder, $prefix, $empty); + } + } + + public function secondColumnHeader($listDirn, $listOrder, $prefix = 'a', $empty = false) { + if ($this->compatible) { + return $this->thOrderingXML('JGRID_HEADING_ORDERING', $listDirn, $listOrder, $prefix, $empty); + } else { + // to do empty + return $this->thCheck('JGLOBAL_CHECK_ALL'); + } + } + + public function startTblBody($saveOrder, $saveOrderingUrl, $listDirn) { + + $o = array(); + + if ($this->compatible) { + $o[] = ''. "\n"; + } + + public function startTr($i, $catid = 0){ + $iD = $i % 2; + if ($this->compatible) { + return ''. "\n"; + } else { + + return ''. "\n"; + } + } + + public function endTr() { + return ''."\n"; + } + + public function firstColumn($i, $itemId, $canChange, $saveOrder, $orderkey, $ordering) { + if ($this->compatible) { + return $this->td( HTMLHelper::_('grid.id', $i, $itemId), 'text-center'); + } else { + return $this->tdOrder($canChange, $saveOrder, $orderkey, $ordering); + } + } + + public function secondColumn($i, $itemId, $canChange, $saveOrder, $orderkey, $ordering) { + + if ($this->compatible) { + + $o = array(); + $o[] = ''; + + $iconClass = ''; + if (!$canChange) { + $iconClass = ' inactive'; + } else if (!$saveOrder) { + $iconClass = ' inactive" title="' . Text::_('JORDERINGDISABLED'); + } + + $o[] = ''; + + if ($canChange && $saveOrder) { + $o[] = ''; + } + + $o[] = ''; + + return implode("", $o); + + } else { + return $this->td(HTMLHelper::_('grid.id', $i, $itemId), "small "); + } + } + + + public function startFilter($txtFilter = ''){ + $o = '
'."\n". JHtmlSidebar::render()."\n"; + + if ($txtFilter != '') { + + + + $o .= '
'."\n" . '
'."\n" + . ''."\n"; + } else { + $o .= '
'; + + } + + return $o; + } + + public function endFilter() { + return '
' . "\n" . '
' . "\n"; + } + + public function startFilterBar($id = 0) { + if ((int)$id > 0) { + return '
'. "\n"; + } else { + return '
'. "\n"; + } + + } + + public function endFilterBar() { + return '
' . "\n" . '
'. "\n"; + } + + + + public function tdImage($item, $button, $txtE, $class = '', $avatarAbs = '', $avatarRel = '') { + $o = ''. "\n"; + $o .= '
'. "\n" + .'
'. "\n" + .'
'. "\n" + .'
'. "\n" + .'
'. "\n" + .'
'. "\n"; + + if ($avatarAbs != '' && $avatarRel != '') { + // AVATAR + if (File::exists($avatarAbs.$item->avatar)){ + $o .= '' + .''.Text::_($txtE).'' + .''; + } else { + $o .= HTMLHelper::_( 'image', '/media/com_phocagallery/images/administrator/phoca_thumb_s_no_image.gif', ''); + } + } else { + // PICASA + if (isset($item->extid) && $item->extid !='') { + + $resW = explode(',', $item->extw); + $resH = explode(',', $item->exth); + $correctImageRes = PhocaGalleryImage::correctSizeWithRate($resW[2], $resH[2], 50, 50); + $imgLink = $item->extl; + + //$o .= '' + $o .= '' + . ''.Text::_($txtE).'' + .''. "\n"; + } else if (isset ($item->fileoriginalexist) && $item->fileoriginalexist == 1) { + + $imageRes = PhocaGalleryImage::getRealImageSize($item->filename, 'small'); + $correctImageRes = PhocaGalleryImage::correctSizeWithRate($imageRes['w'], $imageRes['h'], 50, 50); + $imgLink = PhocaGalleryFileThumbnail::getThumbnailName($item->filename, 'large'); + + //$o .= '' + $o .= '' + . ''.Text::_($txtE).'' + .''. "\n"; + } else { + $o .= HTMLHelper::_( 'image', 'media/com_phocagallery/images/administrator/phoca_thumb_s_no_image.gif', ''); + } + } + $o .= '
'. "\n" + .'
'. "\n" + .'
'. "\n" + .'
'. "\n" + .'
'. "\n" + .'
'. "\n"; + $o .= ''. "\n"; + return $o; + }*/ +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/render/renderfront.php b/administrator/components/com_phocadownload/libraries/phocadownload/render/renderfront.php new file mode 100644 index 00000000..baa304c2 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/render/renderfront.php @@ -0,0 +1,610 @@ +getDocument(); + + $oVars = array(); + $oLang = array(); + $oParams = array(); + /* $oLang = array( + 'COM_PHOCAGALLERY_MAX_LIMIT_CHARS_REACHED' => Text::_('COM_PHOCAGALLERY_MAX_LIMIT_CHARS_REACHED'), + 'COM_PHOCAGALLERY_ENTER_TITLE' => Text::_('COM_PHOCAGALLERY_ENTER_TITLE'), + 'COM_PHOCAGALLERY_ENTER_COMMENT' => Text::_('COM_PHOCAGALLERY_ENTER_COMMENT') + + );*/ + + /// $doc->addScriptOptions('phLangPG', $oLang); + //$doc->addScriptOptions('phVarsPG', $oVars); + //$doc->addScriptOptions('phParamsPG', $oParams); + + + HTMLHelper::_('script', 'media/com_phocadownload/js/main.js', array('version' => 'auto')); + Factory::getApplication() + ->getDocument() + ->getWebAssetManager() + ->useScript('bootstrap.modal'); + } + + public static function renderAllCSS($noBootStrap = 0) { + $app = Factory::getApplication(); + $itemid = $app->input->get('Itemid', 0, 'int'); + $db = Factory::getDBO(); + $query = 'SELECT a.filename as filename, a.type as type, a.menulink as menulink' + .' FROM #__phocadownload_styles AS a' + .' WHERE a.published = 1' + .' ORDER BY a.type, a.ordering ASC'; + $db->setQuery($query); + $filenames = $db->loadObjectList(); + if (!empty($filenames)) { + foreach ($filenames as $fk => $fv) { + + $path = PhocaDownloadFile::getCSSPath($fv->type, 1); + + if ($fv->menulink != '' && (int)$fv->menulink > 1) { + + $menuLinks = explode(',', $fv->menulink); + $isIncluded = in_array((int)$itemid, $menuLinks); + if ($isIncluded) { + HTMLHelper::stylesheet($path . $fv->filename ); + } + } else { + HTMLHelper::stylesheet($path . $fv->filename ); + } + } + } + } + + public static function displayMirrorLinks($view = 1, $link = '', $title = '', $target = '') { + + $paramsC = ComponentHelper::getParams( 'com_phocadownload' ); + $param['display_mirror_links'] = $paramsC->get( 'display_mirror_links', 0 ); + $o = ''; + + $displayM = 0; + if ($view == 1) { + //Category View + if ($param['display_mirror_links'] == 1 || $param['display_mirror_links'] == 3 + || $param['display_mirror_links'] == 4 || $param['display_mirror_links'] == 6) { + $displayM = 1; + } + + } else { + //File View + if ($param['display_mirror_links'] == 2 || $param['display_mirror_links'] == 3 + || $param['display_mirror_links'] == 5 || $param['display_mirror_links'] == 6) { + $displayM = 1; + } + } + + + + if ($displayM == 1 && $link != '' && PhocaDownloadUtils::isURLAddress($link) && $title != '') { + + $targetO = ''; + if ($target != '') { + $targetO = 'target="'.$target.'"'; + } + $o .= ''.strip_tags($title).''; + + } + + return $o; + } + + public static function displayReportLink($view = 1, $title = '') { + + $paramsC = ComponentHelper::getParams( 'com_phocadownload' ); + $param['display_report_link'] = $paramsC->get( 'display_report_link', 0 ); + $param['report_link_guestbook_id'] = $paramsC->get( 'report_link_guestbook_id', 0 ); + $o = ''; + + $displayL = 0; + if ($view == 1) { + //Category View + if ($param['display_report_link'] == 1 || $param['display_report_link'] == 3) { + $displayL = 1; + } + + } else { + //File View + if ($param['display_report_link'] == 2 || $param['display_report_link'] == 3) { + $displayL = 1; + } + } + + if ($displayL == 1 && (int)$param['report_link_guestbook_id'] > 0) { + + $onclick = "window.open(this.href,'win2','width=600,height=500,scrollbars=yes,menubar=no,resizable=yes'); return false;"; + //$href = JRoute::_('index.php?option=com_phocaguestbook&view=guestbook&id='.(int)$param['report_link_guestbook_id'].'&reporttitle='.strip_tags($title).'&tmpl=component&Itemid='. JFactory::getApplication()->input->get('Itemid', 0, '', 'int') ); + + $href = PhocaDownloadRoute::getGuestbookRoute((int)$param['report_link_guestbook_id'],urlencode(strip_tags($title) )); + //$href = JRoute::_('index.php?option=com_phocaguestbook&view=guestbook&id='.(int)$param['report_link_guestbook_id'].'&reporttitle='.strip_tags($title).'&tmpl=component'); + + + $o .= ''.Text::_('COM_PHOCADOWNLOAD_REPORT').''; + + } + + return $o; + } + + public static function displayNewIcon ($date, $time = 0) { + + if ($time == 0) { + return ''; + } + + $dateAdded = strtotime($date, time()); + $dateToday = time(); + $dateExists = $dateToday - $dateAdded; + $dateNew = $time * 24 * 60 * 60; + + + if ($dateExists < $dateNew) { + //return ' '. JHtml::_('image', 'media/com_phocadownload/images/icon-new.png', JText::_('COM_PHOCADOWNLOAD_NEW')); + return ' '.Text::_('COM_PHOCADOWNLOAD_LABEL_TXT_NEW').''; + } else { + return ''; + } + + } + + public static function displayHotIcon ($hits, $requiredHits = 0) { + + if ($requiredHits == 0) { + return ''; + } + + if ($requiredHits <= $hits) { + //return ' '. JHtml::_('image', 'media/com_phocadownload/images/icon-hot.png', JText::_('COM_PHOCADOWNLOAD_HOT')); + return ' '.Text::_('COM_PHOCADOWNLOAD_LABEL_TXT_HOT').''; + } else { + return ''; + } + } + + public static function renderOnUploadJS() { + + $tag = ""; + + return $tag; + } + + public static function renderDescriptionUploadJS($chars) { + + $tag = ""; + + return $tag; + } + + public static function userTabOrdering() { + $js = "\t". '' . "\n"; + + return $js; + } + + public static function renderOverlibCSS($ol_fg_color, $ol_bg_color, $ol_tf_color, $ol_cf_color, $opacity = 0.8) { + + $opacityPer = (float)$opacity * 100; + + $css = "\n"; + + return $css; + } + + public static function renderBootstrapModalJs($item = '.btn') { + + $document = Factory::getDocument(); + HTMLHelper::_('jquery.framework', false); + $s = ' + jQuery(document).ready(function(){ + + jQuery("#phModalPlay").on("hidden.bs.modal", function (e) { + jQuery("#phModalPlay iframe").attr("src", jQuery("#phModalPlay iframe").attr("src")); + jQuery("audio").each(function(){this.pause();this.currentTime = 0;}); + jQuery("video").each(function(){this.pause();this.currentTime = 0;}); + }); + + + jQuery("'.$item.'").on("click", function () { + var $target = jQuery(this).data("target"); + var $href = jQuery(this).data("href"); + var $body = $target + "Body"; + var $dialog = $target + "Dialog"; + var $height = jQuery(this).data("height"); + var $width = jQuery(this).data("width"); + var $heightD= jQuery(this).data("height-dialog"); + var $widthD = jQuery(this).data("width-dialog"); + var $type = jQuery(this).data("type"); + jQuery($body).css("height", $height); + jQuery($target).css("width", $width); + jQuery($body).css("overflow-y", "auto"); + jQuery($dialog).css("height", $heightD); + jQuery($dialog).css("width", $widthD); + + + if ($type == "image") { + jQuery($body).html(\'\'); + } else if ($type == "document") { + $widthD = $widthD -50; + $heightD = $heightD -40; + jQuery($body).html(\'\'); + } else { + + /*jQuery($body).load($href, function (response, status, xhr) { + if (status == "success") { + + + //jQuery($target).modal({ show: true }); + } + });*/ + } + + }); + });'; + $document->addScriptDeclaration($s); + } + + /* Launch + .. + */ + + public static function bootstrapModalHtml($item = 'phModal', $title = '') { + + $close = Text::_('COM_PHOCADOWNLAD_CLOSE'); + $o = ''; + + return $o; + } + + public static function renderPhocaDownload() { + return '
Po' + .'wered by Phoca Down'.'load
'; + } + + public static function renderIcon($type, $img, $alt, $class = '', $attributes = '') { + + //return JHtml::_('image', $img, $alt); + + $paramsC = ComponentHelper::getParams('com_phocadownload'); + + // possible FR + $icons = 0;//$paramsC->get('icons', 0); + + if ($icons == 0) { + return HTMLHelper::_('image', $img, $alt, $attributes); + } + + $i = ''; + + if ($icons == 1) { + + $icon = array(); + $icon['view'] = 'zoom-in'; + $icon['download'] = 'download-alt'; + $icon['geo'] = 'globe'; + $icon['bold'] = 'bold'; + $icon['italic'] = 'italic'; + $icon['underline'] = 'text-color'; + $icon['camera'] = 'camera'; + $icon['comment'] = 'comment'; + $icon['comment-a'] = 'comment'; //ph-icon-animated + $icon['comment-fb'] = 'comment'; //ph-icon-fb + $icon['cart'] = 'shopping-cart'; + $icon['extlink1'] = 'share'; + $icon['extlink2'] = 'share'; + $icon['trash'] = 'trash'; + $icon['publish'] = 'ok'; + $icon['unpublish'] = 'remove'; + $icon['viewed'] = 'modal-window'; + $icon['calendar'] = 'calendar'; + $icon['vote'] = 'star'; + $icon['statistics'] = 'stats'; + $icon['category'] = 'folder-close'; + $icon['subcategory'] = 'folder-open'; + $icon['upload'] = 'upload'; + $icon['upload-ytb'] = 'upload'; + $icon['upload-multiple'] = 'upload'; + $icon['upload-java'] = 'upload'; + $icon['user'] = 'user'; + $icon['icon-up-images'] = 'arrow-left'; + $icon['icon-up'] = 'arrow-up'; + $icon['minus-sign'] = 'minus-sign'; + $icon['next'] = 'forward'; + $icon['prev'] = 'backward'; + $icon['reload'] = 'repeat'; + $icon['play'] = 'play'; + $icon['stop'] = 'stop'; + $icon['pause'] = 'pause'; + $icon['off'] = 'off'; + $icon['image'] = 'picture'; + $icon['save'] = 'floppy-disk'; + $icon['feed'] = 'bullhorn'; + $icon['remove'] = 'remove'; + $icon['search'] = 'zoom-in'; + $icon['lock'] = 'lock'; + + if (isset($icon[$type])) { + return ''; + + } else { + if ($img != '') { + return HTMLHelper::_('image', $img, $alt, $attributes); + } + } + + // NOT glyphicon + // smile, sad, lol, confused, wink, cooliris + + // Classes + // ph-icon-animated, ph-icon-fb, icon-up-images, ph-icon-disabled + + } else if ($icons == 2) { + + $icon = array(); + $icon['view'] = 'search'; + $icon['download'] = 'download'; + $icon['geo'] = 'globe'; + $icon['bold'] = 'bold'; + $icon['italic'] = 'italic'; + $icon['underline'] = 'underline'; + $icon['camera'] = 'camera'; + $icon['comment'] = 'comment'; + $icon['comment-a'] = 'comment'; //ph-icon-animated + $icon['comment-fb'] = 'comment'; //ph-icon-fb + $icon['cart'] = 'shopping-cart'; + $icon['extlink1'] = 'share'; + $icon['extlink2'] = 'share'; + $icon['trash'] = 'trash'; + $icon['publish'] = 'check-circle'; + $icon['unpublish'] = 'times-circle'; + $icon['viewed'] = 'window-maximize'; + $icon['calendar'] = 'calendar'; + $icon['vote'] = 'star'; + $icon['statistics'] = 'chart-bar'; + $icon['category'] = 'folder'; + $icon['subcategory'] = 'folder-open'; + $icon['upload'] = 'upload'; + $icon['upload-ytb'] = 'upload'; + $icon['upload-multiple'] = 'upload'; + $icon['upload-java'] = 'upload'; + $icon['user'] = 'user'; + $icon['icon-up-images'] = 'arrow-left'; + $icon['icon-up'] = 'arrow-up'; + $icon['minus-sign'] = 'minus-circle'; + $icon['next'] = 'forward'; + $icon['prev'] = 'backward'; + $icon['reload'] = 'sync'; + $icon['play'] = 'play'; + $icon['stop'] = 'stop'; + $icon['pause'] = 'pause'; + $icon['off'] = 'power-off'; + $icon['image'] = 'image'; + $icon['save'] = 'save'; + $icon['feed'] = 'rss'; + $icon['remove'] = 'times-circle'; + $icon['search'] = 'search'; + $icon['lock'] = 'lock'; + + + if (isset($icon[$type])) { + return ''; + + } else { + if ($img != '') { + return HTMLHelper::_('image', $img, $alt, $attributes); + } + } + } + } + + public static function renderHeader($headers = array(), $tag = '', $imageMeta = '') + { + + $app = Factory::getApplication(); + //$menus = $app->getMenu(); + //$menu = $menus->getActive(); + $p = $app->getParams(); + $showPageHeading = $p->get('show_page_heading'); + $pageHeading = $p->get('page_heading'); + $displayHeader = $p->get('display_header_type', 'h1'); + //$hideHeader = $p->get('hide_header_view', array()); + + + + if ($displayHeader == '-1') { + return ''; + } + + //$view = $app->input->get('view', '', 'string'); + + /*if (!empty($hideHeader) && $view != '') { + if (in_array($view, $hideHeader)) { + return ''; + } + + }*/ + + + if ($tag == '') { + $tag = $displayHeader; + } + + $h = array(); + if ($showPageHeading && $pageHeading != '') { + $h[] = htmlspecialchars($pageHeading); + } + + if (!empty($headers)) { + foreach ($headers as $k => $v) { + if ($v != '') { + $h[] = htmlspecialchars($v); + break; // in array there are stored OR items (if empty try next, if not empty use this and do not try next) + // PAGE HEADING AND NEXT ITEM OR NEXT NEXT ITEM + } + } + } + + $imgMetaAttr = ''; + if ($imageMeta != '') { + $imgMetaAttr = 'data-image-meta="'.$imageMeta.'"'; + } + + if (!empty($h)) { + return '<' . strip_tags($tag) . ' class="ph-header" '.$imgMetaAttr.'>' . implode(" - ", $h) . ''; + } else if ($imgMetaAttr != '') { + return '
';// use hidden tag for open graph info + } + return false; + } + + public static function renderSubHeader($headers = array(), $tag = '', $class = '', $imageMeta = '') + { + + $app = Factory::getApplication(); + //$menus = $app->getMenu(); + //$menu = $menus->getActive(); + $p = $app->getParams(); + //$showPageHeading = $p->get('show_page_heading'); + //$pageHeading = $p->get('page_heading'); + $displayHeader = $p->get('display_subheader_type', 'h3'); + //$hideHeader = $p->get('hide_header_view', array()); + + + + if ($displayHeader == '-1') { + return ''; + } + + //$view = $app->input->get('view', '', 'string'); + + /*if (!empty($hideHeader) && $view != '') { + if (in_array($view, $hideHeader)) { + return ''; + } + + }*/ + + + if ($tag == '') { + $tag = $displayHeader; + } + + $h = array(); + // if ($showPageHeading && $pageHeading != '') { + // $h[] = htmlspecialchars($pageHeading); + // } + + if (!empty($headers)) { + foreach ($headers as $k => $v) { + if ($v != '') { + $h[] = htmlspecialchars($v); + break; // in array there are stored OR items (if empty try next, if not empty use this and do not try next) + // PAGE HEADING AND NEXT ITEM OR NEXT NEXT ITEM + } + } + } + + $imgMetaAttr = ''; + if ($imageMeta != '') { + $imgMetaAttr = 'data-image-meta="'.$imageMeta.'"'; + } + + if (!empty($h)) { + return '<' . strip_tags($tag) . ' class="ph-subheader '.htmlspecialchars(strip_tags($class)).'" '.$imgMetaAttr.'>' . implode(" - ", $h) . ''; + } else if ($imgMetaAttr != '') { + return '
';// use hidden tag for open graph info + } + return false; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/render/rendertabs.php b/administrator/components/com_phocadownload/libraries/phocadownload/render/rendertabs.php new file mode 100644 index 00000000..b1a25b49 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/render/rendertabs.php @@ -0,0 +1,85 @@ +id = uniqid(); + HTMLHelper::_('jquery.framework', false); + HTMLHelper::_('script', 'media/com_phocadownload/js/tabs/tabs.js', array('version' => 'auto')); + HTMLHelper::_('stylesheet', 'media/com_phocadownload/js/tabs/tabs.css', array('version' => 'auto')); + } + + public function setActiveTab($item) { + if ($item != '') { + $this->activeTab = $item; + } + } + + public function startTabs() { + return '
'; + } + + + public function endTabs() { + return '
'; + } + + public function renderTabsHeader($items) { + + $o = array(); + $o[] = ''; + return implode("\n", $o); + + } + + public function startTab($name) { + + $activeO = ''; + if ($this->activeTab == '' && $this->countTab == 0) { + $activeO = ' active'; + } else if ($this->activeTab == $name) { + $activeO = ' active'; + } + $this->countTab++; + return '
'; + } + + public function endTab() { + return '
'; + } +} + diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/stat/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/stat/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/stat/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/stat/stat.php b/administrator/components/com_phocadownload/libraries/phocadownload/stat/stat.php new file mode 100644 index 00000000..19cf5cad --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/stat/stat.php @@ -0,0 +1,85 @@ +quoteName('#__phocadownload_user_stat') + .' WHERE '. $db->quoteName('userid') + .' = ' + .$db->Quote((int)$user->id) + .' AND '. $db->quoteName('fileid') + .' = ' + .$db->Quote((int)$downloadId); + + $db->setQuery($query); + $results = $db->loadObjectList(); + + $date = gmdate('Y-m-d H:i:s'); + if ($results) { + // Update count + $query = 'UPDATE '.$db->quoteName('#__phocadownload_user_stat') + .' SET count = (count + 1),' + .' date = '.$db->Quote($date) + .' WHERE userid = '.$db->Quote((int)$user->id) + .' AND fileid = '.$db->Quote((int)$downloadId); + + $db->setQuery($query); + $db->execute(); + } else { + + $query = 'INSERT INTO '.$db->quoteName('#__phocadownload_user_stat') + .' ('.$db->quoteName('count').',' + .' '.$db->quoteName('userid').',' + .' '.$db->quoteName('fileid').',' + .' '.$db->quoteName('date').')' + .' VALUES ('.$db->Quote(1).',' + .' '.$db->Quote((int)$user->id).',' + .' '.$db->Quote((int)$downloadId).',' + .' '.$db->Quote($date).')'; + $db->setQuery($query); + $db->execute(); + } + return true; + } + + public static function getCountFilePerUser($downloadId) { + $db = Factory::getDBO(); + $user = Factory::getUser(); + + $query = ' SELECT count FROM '.$db->quoteName('#__phocadownload_user_stat') + .' WHERE '. $db->quoteName('userid') + .' = ' + .$db->Quote((int)$user->id) + .' AND '. $db->quoteName('fileid') + .' = ' + .$db->Quote((int)$downloadId) + .' LIMIT 0, 1'; + + $db->setQuery($query); + $count = $db->loadObject(); + if (isset($count->count)) { + return (int)$count->count; + } else { + return 0; + } + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/tag/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/tag/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/tag/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/tag/tag.php b/administrator/components/com_phocadownload/libraries/phocadownload/tag/tag.php new file mode 100644 index 00000000..a821ef8a --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/tag/tag.php @@ -0,0 +1,120 @@ +setQuery($query); + + /*if (!$db->query()) { + echo PhocaDownloadException::renderErrorInfo('Database Error - Getting Selected Tags'); + return false; + }*/ + if ($select == 1) { + $tags = $db->loadColumn(); + } else { + $tags = $db->loadObjectList(); + } + + return $tags; + } + + public static function storeTags($tagsArray, $fileId) { + + + if ((int)$fileId > 0) { + $db = Factory::getDBO(); + $query = ' DELETE ' + .' FROM #__phocadownload_tags_ref' + . ' WHERE fileid = '. (int)$fileId; + $db->setQuery($query); + if (!$db->execute()) { + echo PhocaDownloadException::renderErrorInfo('Database Error - Deleting FileId Tags'); + return false; + } + + if (!empty($tagsArray)) { + + $values = array(); + $valuesString = ''; + + foreach($tagsArray as $k => $v) { + $values[] = ' ('.(int)$fileId.', '.(int)$v.')'; + } + + if (!empty($values)) { + $valuesString = implode(',', $values); + + $query = ' INSERT INTO #__phocadownload_tags_ref (fileid, tagid)' + .' VALUES '.(string)$valuesString; + + $db->setQuery($query); + if (!$db->execute()) { + echo PhocaDownloadException::renderErrorInfo('Database Error - Insert FileId Tags'); + return false; + } + + } + } + } + + } + + public static function getAllTagsSelectBox($name, $id, $activeArray, $javascript = NULL, $order = 'id' ) { + + $db = Factory::getDBO(); + $query = 'SELECT a.id AS value, a.title AS text' + .' FROM #__phocadownload_tags AS a' + . ' ORDER BY '. $order; + //. ' ORDER BY a.id'; + $db->setQuery($query); + + /*if (!$db->execute()) { + echo PhocaDownloadException::renderErrorInfo('Database Error - Getting All Tags'); + return false; + }*/ + + $tags = $db->loadObjectList(); + + $tagsO = HTMLHelper::_('select.genericlist', $tags, $name, 'class="form-select" size="4" multiple="multiple"'. $javascript, 'value', 'text', $activeArray, $id); + + return $tagsO; + } + + public static function getAllTags($order = 'id' ) { + + $db =Factory::getDBO(); + $query = 'SELECT a.id AS value, a.title AS text' + .' FROM #__phocadownload_tags AS a' + . ' ORDER BY '. $order; + $db->setQuery($query); + + + + $tags = $db->loadObjectList(); + + return $tags; + } +} diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/user/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/user/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/user/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/user/user.php b/administrator/components/com_phocadownload/libraries/phocadownload/user/user.php new file mode 100644 index 00000000..bfa2cc04 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/user/user.php @@ -0,0 +1,143 @@ +get( 'user_ucp_lang', 1 ); + + $o = array(); + + switch ($userLang){ + case 2: + $registry = new Registry; + $registry->loadString($user->params); + $o['lang'] = $registry->get('language','*'); + $o['langinput'] = ''; + break; + + case 3: + $o['lang'] = Factory::getLanguage()->getTag(); + $o['langinput'] = ''; + break; + + default: + case 1: + $o['lang'] = '*'; + $o['langinput'] = ''; + break; + } + return $o; + } + + public static function getUserFileInfo($file, $userId) { + + $db = Factory::getDBO(); + $allFile['size'] = 0; + $allFile['count'] = 0; + $query = 'SELECT SUM(a.filesize) AS sumfiles, COUNT(a.id) AS countfiles' + .' FROM #__phocadownload AS a' + .' WHERE a.owner_id = '.(int)$userId; + $db->setQuery($query, 0, 1); + $fileData = $db->loadObject(); + + if(isset($fileData->sumfiles) && (int)$fileData->sumfiles > 0) { + $allFile['size'] = (int)$allFile['size'] + (int)$fileData->sumfiles; + } + + if (isset($file['size'])) { + $allFile['size'] = (int)$allFile['size'] + (int)$file['size']; + $allFile['count'] = (int)$fileData->countfiles + 1; + } + + return $allFile; + } + + /** + * Method to display multiple select box + * @param string $name Name (id, name parameters) + * @param array $active Array of items which will be selected + * @param int $nouser Select no user + * @param string $javascript Add javascript to the select box + * @param string $order Ordering of items + * @param int $reg Only registered users + * @return array of id + */ + + public static function usersList( $name, $id, $active, $nouser = 0, $javascript = NULL, $order = 'name', $reg = 1, $returnArray = 0) { + + $activeArray = $active; + if ($active != '') { + $activeArray = explode(',',$active); + } + + $db = Factory::getDBO(); + $and = ''; + if ($reg) { + // does not include registered users in the list + $and = ' AND m.group_id != 2'; + } + + $query = 'SELECT u.id AS value, u.name AS text' + . ' FROM #__users AS u' + . ' JOIN #__user_usergroup_map AS m ON m.user_id = u.id' + . ' WHERE u.block = 0' + . $and + . ' GROUP BY u.id' + . ' ORDER BY '. $order; + + + + $db->setQuery( $query ); + if ( $nouser ) { + + // Access rights (Default open for all) + // Upload and Delete rights (Default closed for all) + switch ($name) { + case 'jform[accessuserid][]': + $idInput1 = -1; + $idText1 = Text::_( 'COM_PHOCADOWNLOAD_ALL_REGISTERED_USERS' ); + $idInput2 = -2; + $idText2 = Text::_( 'COM_PHOCADOWNLOAD_NOBODY' ); + break; + + Default: + $idInput1 = -2; + $idText1 = Text::_( 'COM_PHOCADOWNLOAD_NOBODY' ); + $idInput2 = -1; + $idText2 = Text::_( 'COM_PHOCADOWNLOAD_ALL_REGISTERED_USERS' ); + break; + } + + $users[] = HTMLHelper::_('select.option', $idInput1, '- '. $idText1 .' -' ); + $users[] = HTMLHelper::_('select.option', $idInput2, '- '. $idText2 .' -' ); + + $users = array_merge( $users, $db->loadObjectList() ); + } else { + $users = $db->loadObjectList(); + } + + if ($returnArray == 1) { + return $users; + } + + $users = HTMLHelper::_('select.genericlist', $users, $name, 'class="form-select" size="4" multiple="multiple"'. $javascript, 'value', 'text', $activeArray, $id ); + + return $users; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/utils/exception.php b/administrator/components/com_phocadownload/libraries/phocadownload/utils/exception.php new file mode 100644 index 00000000..72f36776 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/utils/exception.php @@ -0,0 +1,26 @@ +'.Text::_($msg).'
'; + } else { + return '
'.$msg.'
'; + } + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/utils/external.php b/administrator/components/com_phocadownload/libraries/phocadownload/utils/external.php new file mode 100644 index 00000000..3d337b1a --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/utils/external.php @@ -0,0 +1,24 @@ +checkAccess('phoca', 'category', $fileName->catid); + } else if (file_exists(JPATH_ADMINISTRATOR . "/components/com_osemsc/warehouse/api.php")) { + require_once (JPATH_ADMINISTRATOR . "/components/com_osemsc/warehouse/api.php"); + $checkmsc = new OSEMSCAPI(); + $checkmsc->ACLCheck("phoca", "cat", $fileName->catid, true); + } + } +} +?> \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/utils/index.html b/administrator/components/com_phocadownload/libraries/phocadownload/utils/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/utils/index.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/utils/settings.php b/administrator/components/com_phocadownload/libraries/phocadownload/utils/settings.php new file mode 100644 index 00000000..fc4cc812 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/utils/settings.php @@ -0,0 +1,127 @@ +setQuery($query, 0, 1); + $layout = $db->loadObject(); + + /*if (!$db->query()) { + throw new Exception($db->getErrorMsg(), 500); + return false; + }*/ + + if (isset($layout->$type)) { + return $layout->$type; + } + + return ''; + + } + + public static function getLayoutParams($type) { + + $params = array(); + switch($type) { + + case 'categories': + $params['style'] = array('pd-title','pd-desc', 'pd-subcategory', 'pd-no-subcat');//'pd-', + $params['search'] = array('{pdtitle}','{pddescription}', '{pdsubcategories}', '{pdclear}'); + break; + + case 'category': + $params['style'] = array('pd-title','pd-image', 'pd-file', 'pd-fdesc', 'pd-mirrors', 'pd-mirror', 'pd-report', 'pd-rating', 'pd-tags', 'pd-buttons', 'pd-downloads', 'pd-video'); + $params['search'] = array('{pdtitle}','{pdimage}', '{pdfile}', '{pdfilesize}', '{pdversion}', '{pdlicense}', '{pdauthor}', '{pdauthoremail}', '{pdfiledate}', '{pddownloads}', '{pddescription}', '{pdfeatures}', '{pdchangelog}', '{pdnotes}', '{pdmirrorlink1}', '{pdmirrorlink2}', '{pdreportlink}', '{pdrating}', '{pdtags}', '{pdfiledesctop}', '{pdfiledescbottom}', '{pdbuttondownload}', '{pdbuttondetails}', '{pdbuttonpreview}', '{pdbuttonplay}', '{pdvideo}'); + break; + + + case 'file': + $params['style'] = array('pd-title','pd-image', 'pd-file', 'pd-fdesc', 'pd-mirrors', 'pd-mirror', 'pd-report', 'pd-rating', 'pd-tags', 'pd-downloads', 'pd-video'); + $params['search'] = array('{pdtitle}','{pdimage}', '{pdfile}', '{pdfilesize}', '{pdversion}', '{pdlicense}', '{pdauthor}', '{pdauthoremail}', '{pdfiledate}', '{pddownloads}', '{pddescription}', '{pdfeatures}', '{pdchangelog}', '{pdnotes}', '{pdmirrorlink1}', '{pdmirrorlink2}', '{pdreportlink}', '{pdrating}', '{pdtags}', '{pdvideo}'); + break; + } + + return $params; + } +} +?> diff --git a/administrator/components/com_phocadownload/libraries/phocadownload/utils/utils.php b/administrator/components/com_phocadownload/libraries/phocadownload/utils/utils.php new file mode 100644 index 00000000..7022b661 --- /dev/null +++ b/administrator/components/com_phocadownload/libraries/phocadownload/utils/utils.php @@ -0,0 +1,239 @@ +Powe'.'red b'.'y Pho' + .'ca Downl'.'oad
'; + } + + public static function getExtensionVersion($c = 'phocadownload') { + $folder = JPATH_ADMINISTRATOR .'/components/com_'.$c; + if (Folder::exists($folder)) { + $xmlFilesInDir = Folder::files($folder, '.xml$'); + } else { + $folder = JPATH_SITE . '/components/com_'.$c; + if (Folder::exists($folder)) { + $xmlFilesInDir = Folder::files($folder, '.xml$'); + } else { + $xmlFilesInDir = null; + } + } + + $xml_items = array(); + if (count($xmlFilesInDir)) + { + foreach ($xmlFilesInDir as $xmlfile) + { + if ($data = Installer::parseXMLInstallFile($folder.'/'.$xmlfile)) { + foreach($data as $key => $value) { + $xml_items[$key] = $value; + } + } + } + } + + if (isset($xml_items['version']) && $xml_items['version'] != '' ) { + return $xml_items['version']; + } else { + return ''; + } + } + + public static function setVars( $task = '') { + + $a = array(); + $app = Factory::getApplication(); + $a['o'] = htmlspecialchars(strip_tags($app->input->get('option'))); + $a['c'] = str_replace('com_', '', $a['o']); + $a['n'] = 'Phoca' . ucfirst(str_replace('com_phoca', '', $a['o'])); + $a['l'] = strtoupper($a['o']); + $a['i'] = 'media/'.$a['o'].'/images/administrator/'; + $a['s'] = 'media/'.$a['o'].'/css/administrator/'.$a['c'].'.css'; + $a['task'] = $a['c'] . htmlspecialchars(strip_tags($task)); + $a['tasks'] = $a['task']. 's'; + return $a; + } + + public static function getAliasName($alias) { + $alias = ApplicationHelper::stringURLSafe($alias); + if (trim(str_replace('-', '', $alias)) == '') { + $alias = Factory::getDate()->format("Y-m-d-H-i-s"); + } + return $alias; + + } + + public static function strTrimAll($input) { + $output = ''; + $input = trim($input); + for($i=0;$i 0); + } else if (empty($value)) { + return array(0 => 0); + } else if (is_array($value)) { + return $value; + } else { + return array(0 => $value); + } + + } + public static function isURLAddress($url) { + return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url); + } + + public static function setQuestionmarkOrAmp($url) { + $isThereQMR = false; + $isThereQMR = preg_match("/\?/i", $url); + if ($isThereQMR) { + return '&'; + } else { + return '?'; + } + } + + public static function getToken($title = '') { + $salt = md5($title . 'string '. date('s'). mt_rand(0,9999) . str_replace(mt_rand(0,9), mt_rand(0,9999), date('r')). 'end string'); + $token = hash('sha256', $salt . time()); + return $token; + } + + public static function cleanFolderUrlName($string) { + $string = str_replace('@', '-', $string); + $string = str_replace('?', '-', $string); + $string = str_replace('&', '-', $string); + $string = str_replace('%', '-', $string); + return $string; + + } + + public static function getIntFromString($string) { + + if (empty($string)) { + return 0; + } + $int = '';//$int = 0 + $parts = explode(':', $string); + if (isset($parts[0])) { + $int = (int)$parts[0]; + } + return $int; + } + + public static function getInfo() { + + PluginHelper::importPlugin('phocatools'); + $results = Factory::getApplication()->triggerEvent('onPhocatoolsOnDisplayInfo', array('NjI5NTcxNzcxMTc=')); + if (isset($results[0]) && $results[0] === true) { + return ''; + } + return '
Powered by Phoca Download
'; + + } + + + + public static function filterValue($string, $type = 'html') { + + switch ($type) { + + case 'url': + return rawurlencode($string); + break; + + case 'number': + return preg_replace( '/[^.0-9]/', '', (string)$string ); + break; + + case 'number2': + //return preg_replace( '/[^0-9\.,+-]/', '', $string ); + return preg_replace( '/[^0-9\.,-]/', '', (string)$string ); + break; + + case 'alphanumeric': + return preg_replace("/[^a-zA-Z0-9]+/", '', (string)$string); + break; + + case 'alphanumeric2': + return preg_replace("/[^\\w-]/", '', (string)$string);// Alphanumeric plus _ - + break; + + case 'alphanumeric3': + return preg_replace("/[^\\w.-]/", '', (string)$string);// Alphanumeric plus _ . - + break; + + case 'folder': + case 'file': + $string = preg_replace('/[\"\*\/\\\:\<\>\?\'\|]+/', '', (string)$string); + return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); + break; + + case 'folderpath': + case 'filepath': + $string = preg_replace('/[\"\*\:\<\>\?\'\|]+/', '', (string)$string); + return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); + break; + + case 'text': + return htmlspecialchars(strip_tags((string)$string), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); + break; + + case 'html': + default: + return htmlspecialchars((string)$string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); + break; + + } + + } + + public static function getIp() { + + + $params = ComponentHelper::getParams('com_phocadownload'); + $store_ip = $params->get( 'store_ip', 0 ); + + if ($store_ip == 0) { + return ''; + } + + $ip = false; + if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] != getenv('SERVER_ADDR')) { + $ip = $_SERVER['REMOTE_ADDR']; + } else { + $ip = getenv('HTTP_X_FORWARDED_FOR'); + } + if (!$ip) { + $ip = $_SERVER['REMOTE_ADDR']; + } + + return $ip; + } +} +?>