Beispiel #1
0
 /**
  * Set up to display the entity selection view
  *
  * This allows users to select entities (sections, categories, and other
  * content items that are supported with Attachments plugins).
  */
 public function selectEntity()
 {
     // Get the parent type
     $parent_type = JRequest::getCmd('parent_type');
     if (!$parent_type) {
         $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $parent_type) . $db->getErrorMsg() . ' (ERR 65)';
         JError::raiseError(500, $errmsg);
     }
     // Parse the parent type and entity
     $parent_entity = JRequest::getCmd('parent_entity', 'default');
     if (strpos($parent_type, '.')) {
         $parts = explode('.', $parent_type);
         $parent_type = $parts[0];
         $parent_entity = $parts[1];
     }
     // Get the content parent object
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     $parent = $apm->getAttachmentsPlugin($parent_type);
     $parent_entity = $parent->getCanonicalEntityId($parent_entity);
     $parent_entity_name = JText::_('ATTACH_' . $parent_entity);
     // Get the URL to repost (for filtering)
     $post_url = $parent->getSelectEntityURL($parent_entity);
     // Set up the display lists
     $lists = array();
     // table ordering
     $app = JFactory::getApplication();
     $filter_order = $app->getUserStateFromRequest('com_attachments.selectEntity.filter_order', 'filter_order', '', 'cmd');
     $filter_order_Dir = $app->getUserStateFromRequest('com_attachments.selectEntity.filter_order_Dir', 'filter_order_Dir', '', 'word');
     $lists['order_Dir'] = $filter_order_Dir;
     $lists['order'] = $filter_order;
     // search filter
     $search_filter = $app->getUserStateFromRequest('com_attachments.selectEntity.search', 'search', '', 'string');
     $lists['search'] = $search_filter;
     // Get the list of items to display
     $items = $parent->getEntityItems($parent_entity, $search_filter);
     // Set up the view
     require_once JPATH_COMPONENT_ADMINISTRATOR . '/views/entity/view.html.php';
     $view = new AttachmentsViewEntity();
     $view->option = JRequest::getCmd('option');
     $view->from = 'closeme';
     $view->post_url = $post_url;
     $view->parent_type = $parent_type;
     $view->parent_entity = $parent_entity;
     $view->parent_entity_name = $parent_entity_name;
     $view->lists = $lists;
     $view->items = $items;
     $view->display();
 }
Beispiel #2
0
 /**
  * Override the getItem() command to get some extra info
  *
  * @param	integer	$pk	The id of the primary key.
  *
  * @return	mixed	Object on success, false on failure.
  */
 public function getItem($pk = null)
 {
     $item = parent::getItem($pk);
     if ($item->id != 0) {
         // If the item exists, get more info
         $db = $this->getDbo();
         // Get the creator name
         $query = $db->getQuery(true);
         $query->select('name')->from('#__users')->where('id = ' . (int) $item->created_by);
         $db->setQuery($query, 0, 1);
         $item->creator_name = $db->loadResult();
         if ($db->getErrorNum()) {
             $errmsg = $db->stderr() . ' (ERR 112)';
             JError::raiseError(500, $errmsg);
         }
         // Get the modifier name
         $query = $db->getQuery(true);
         $query->select('name')->from('#__users')->where('id = ' . (int) $item->modified_by);
         $db->setQuery($query, 0, 1);
         $item->modifier_name = $db->loadResult();
         if ($db->getErrorNum()) {
             $errmsg = $db->stderr() . ' (ERR 113)';
             JError::raiseError(500, $errmsg);
         }
         // Get the parent info (??? Do we really need this?)
         $parent_type = $item->parent_type;
         $parent_entity = $item->parent_entity;
         JPluginHelper::importPlugin('attachments');
         $apm = getAttachmentsPluginManager();
         if (!$apm->attachmentsPluginInstalled($parent_type)) {
             $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $parent_type) . ' (ERR 114)';
             JError::raiseError(500, $errmsg);
         }
         $item->parent = $apm->getAttachmentsPlugin($parent_type);
     }
     return $item;
 }
Beispiel #3
0
 /**
  * Load the attachment data
  *
  * @return true if loaded successfully
  */
 private function _loadAttachment()
 {
     if ($this->_id == 0) {
         return false;
     }
     if (empty($this->_attachment)) {
         $user = JFactory::getUser();
         $user_levels = $user->getAuthorisedViewLevels();
         // If the user is not logged in, add extra view levels (if configured)
         if ($user->get('username') == '') {
             // Get the component parameters
             jimport('joomla.application.component.helper');
             $params = JComponentHelper::getParams('com_attachments');
             // Add the specified access levels
             $guest_levels = $params->get('show_guest_access_levels', array('1'));
             if (is_array($guest_levels)) {
                 foreach ($guest_levels as $glevel) {
                     $user_levels[] = $glevel;
                 }
             } else {
                 $user_levels[] = $glevel;
             }
         }
         $user_levels = implode(',', array_unique($user_levels));
         // Load the attachment data and make sure this user has access
         $db = $this->getDbo();
         $query = $db->getQuery(true);
         $query->select('a.*, a.id as id');
         $query->from('#__attachments as a');
         $query->where('a.id = ' . (int) $this->_id);
         if (!$user->authorise('core.admin')) {
             $query->where('a.access in (' . $user_levels . ')');
         }
         $db->setQuery($query, 0, 1);
         $this->_attachment = $db->loadObject();
         if (empty($this->_attachment)) {
             return false;
         }
         // Retrieve the information about the parent
         $parent_type = $this->_attachment->parent_type;
         $parent_entity = $this->_attachment->parent_entity;
         JPluginHelper::importPlugin('attachments');
         $apm = getAttachmentsPluginManager();
         if (!$apm->attachmentsPluginInstalled($parent_type)) {
             $this->_attachment->parent_type = false;
             return false;
         }
         $parent = $apm->getAttachmentsPlugin($parent_type);
         // Set up the parent info
         $parent_id = $this->_attachment->parent_id;
         $this->_attachment->parent_title = $parent->getTitle($parent_id, $parent_entity);
         $this->_attachment->parent_published = $parent->isParentPublished($parent_id, $parent_entity);
     }
     return true;
 }
Beispiel #4
0
 /**
  * Show a list of all attachment IDs
  *
  * This is for system testing purposes only
  */
 public function listKnownParentTypes()
 {
     // Get the article/parent handler
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     $ptypes = $apm->getInstalledParentTypes();
     echo implode($ptypes, '<br/>');
 }
Beispiel #5
0
 /**
  * Method to set the publishing state for a row or list of rows in the database
  * table.  The method respects checked out rows by other users and will attempt
  * to checkin rows that it can after adjustments are made.
  *
  * @param	mixed	An optional array of primary key values to update.	If not
  *					set the instance property value is used.
  * @param	integer The publishing state. eg. [0 = unpublished, 1 = published]
  * @param	integer The user id of the user performing the operation.
  * @return	int Number of attachments published ( false if 0 )
  * @since	1.0.4
  * @link	http://docs.joomla.org/JTable/publish
  */
 public function publish($pks = null, $state = 1, $userId = 0)
 {
     // Initialise variables.
     $k = $this->_tbl_key;
     // Sanitize input.
     JArrayHelper::toInteger($pks);
     $userId = (int) $userId;
     $state = (int) $state;
     // If there are no primary keys set check to see if the instance key is set.
     if (empty($pks)) {
         if ($this->{$k}) {
             $pks = array($this->{$k});
         } else {
             $e = new JException(JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED'));
             $this->setError($e);
             return false;
         }
     }
     // Get the article/parent handler
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     // Remove any attachments that the user may not publish/unpublish
     $bad_ids = array();
     foreach ($pks as $id) {
         // Get the info about this attachment
         $query = $this->_db->getQuery(true);
         $query->select('*')->from($this->_tbl);
         $query->where('id=' . (int) $id);
         $this->_db->setQuery($query);
         $attachment = $this->_db->loadObject();
         if ($this->_db->getErrorNum()) {
             $errmsg = $db->stderr() . ' (ERR 108)';
             JError::raiseError(500, $errmsg);
         }
         $parent_id = $attachment->parent_id;
         $parent_type = $attachment->parent_type;
         $parent_entity = $attachment->parent_entity;
         if (!$apm->attachmentsPluginInstalled($parent_type)) {
             $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $parent_type) . ' (ERR 109)';
             JError::raiseError(500, $errmsg);
         }
         $parent = $apm->getAttachmentsPlugin($parent_type);
         // If we may not change it's state, complain!
         if (!$parent->userMayChangeAttachmentState($parent_id, $parent_entity, $attachment->created_by)) {
             // Note the bad ID
             $bad_ids[] = $id;
             // If the user is not authorized, complain
             $app = JFactory::getApplication();
             $parent_entity = $parent->getCanonicalEntityId($parent_entity);
             $errmsg = JText::sprintf('ATTACH_ERROR_NO_PERMISSION_TO_PUBLISH_S_ATTACHMENT_S_ID_N', $parent_entity, $attachment->filename, $id) . ' (ERR 110)';
             $app->enqueueMessage($errmsg, 'error');
         }
     }
     // Remove any offending attachments
     $pks = array_diff($pks, $bad_ids);
     // Exit if there are no attachments the user can change the state of
     if (empty($pks)) {
         // No warning needed because warnings already issued for attachments user cannot change
         return false;
     }
     // Update the publishing state for rows with the given primary keys.
     $query = $this->_db->getQuery(true);
     $query->update($this->_tbl);
     $query->set('state = ' . (int) $state);
     // Determine if there is checkin support for the table.
     if (property_exists($this, 'checked_out') || property_exists($this, 'checked_out_time')) {
         $query->where('(checked_out = 0 OR checked_out = ' . (int) $userId . ')');
         $checkin = true;
     } else {
         $checkin = false;
     }
     // Build the WHERE clause for the primary keys.
     $query->where($k . ' = ' . implode(' OR ' . $k . ' = ', $pks));
     $this->_db->setQuery($query);
     // Check for a database error.
     if (!$this->_db->query()) {
         $e = new JException(JText::sprintf('JLIB_DATABASE_ERROR_PUBLISH_FAILED', get_class($this), $this->_db->getErrorMsg()) . ' (ERR 111)');
         $this->setError($e);
         return false;
     }
     // If checkin is supported and all rows were adjusted, check them in.
     if ($checkin && count($pks) == $this->_db->getAffectedRows()) {
         // Checkin the rows.
         foreach ($pks as $pk) {
             $this->checkin($pk);
         }
     }
     // If the JTable instance value is in the list of primary keys that were set, set the instance.
     if (in_array($this->{$k}, $pks)) {
         $this->state = $state;
     }
     $this->setError('');
     return count($pks);
 }
 /**
  * Inserts the attachments list above the row of xtd-buttons
  *
  * And in older versions, inserts the attachments list for category
  * descriptions.
  *
  * @access	public
  * @since	1.5
  */
 public function onAfterRender()
 {
     $task = JRequest::getCmd('task');
     $view = JRequest::getCmd('view');
     $layout = JRequest::getWord('layout');
     // Make sure this we should handle this
     $parent_type = JRequest::getCMD('option');
     if (!$parent_type) {
         return;
     }
     // Handle the special case of Global Config for Attachments 3.x
     if (version_compare(JVERSION, '3.0', 'ge')) {
         if ($parent_type == 'com_config' and $task == '' and $view == '') {
             // Force use of the Attachments options editor
             // option=com_config&view=component&component=com_attachments
             $body = JResponse::getBody();
             $body = str_replace('option=com_config&view=component&component=com_attachments', 'option=com_attachments&task=params.edit', $body);
             JResponse::setBody($body);
         }
     }
     // Handle attachments
     $parent_entity = 'default';
     // Handle categories specially (since they are really com_content)
     if ($parent_type == 'com_categories') {
         $parent_type = 'com_content';
         $parent_entity = 'category';
     }
     // Get the article/parent handler
     if (!JPluginHelper::importPlugin('attachments')) {
         // Exit if the framework does not exist (eg, during uninstallaton)
         return false;
     }
     if (!function_exists('getAttachmentsPluginManager')) {
         // Exit if the function does not exist (eg, during uninstallaton)
         return false;
     }
     $apm = getAttachmentsPluginManager();
     if (!$apm->attachmentsPluginInstalled($parent_type)) {
         // Exit if there is no Attachments plugin to handle this parent_type
         return false;
     }
     $parent = $apm->getAttachmentsPlugin($parent_type);
     // Get the parent ID
     $parent_entity = $parent->getCanonicalEntityId($parent_entity);
     $parent_id = $parent->getParentIdInEditor($parent_entity, $view, $layout);
     // Exit if we do not have an parent (exiting or being created)
     if ($parent_id === false) {
         return;
     }
     // See if this type of content suports displaying attachments in its editor
     if ($parent->showAttachmentsInEditor($parent_entity, $view, $layout)) {
         // Get the article/parent handler
         $user_can_add = $parent->userMayAddAttachment($parent_id, $parent_entity);
         // Allow remapping of parent ID (eg, for Joomfish)
         if (jimport('attachments_remapper.remapper')) {
             $parent_id = AttachmentsRemapper::remapParentID($parent_id, $parent_type, $parent_entity);
         }
         // Force the ID to zero when creating the entity
         if (!$parent_id) {
             $parent_id = 0;
         }
         // Construct the attachment list
         $Itemid = JRequest::getInt('Itemid', 1);
         $from = 'editor';
         $attachments = AttachmentsHelper::attachmentsListHTML($parent_id, $parent_type, $parent_entity, $user_can_add, $Itemid, $from, false, true);
         // If the attachments list is empty, insert an empty div for it
         if ($attachments == '') {
             jimport('joomla.application.component.helper');
             $params = JComponentHelper::getParams('com_attachments');
             $class_name = $params->get('attachments_table_style', 'attachmentsList');
             $div_id = 'attachmentsList' . '_' . $parent_type . '_' . $parent_entity . '_' . (string) $parent_id;
             $attachments = "\n<div class=\"{$class_name}\" id=\"{$div_id}\"></div>\n";
         }
         // Insert the attachments above the editor buttons
         // NOTE: Assume that anyone editing the article can see its attachments
         $body = $parent->insertAttachmentsListInEditor($parent_id, $parent_entity, $attachments, JResponse::getBody());
         JResponse::setBody($body);
     } elseif ($parent_id && $view == 'category') {
         // Only dislay this in the front end
         $app = JFactory::getApplication();
         if ($app->isAdmin()) {
             return;
         }
         // More recent versions of Joomla allow this to be handled better
         // by the normal Attachments onContentPrepare callback
         if (version_compare(JVERSION, '3.1', 'ge') or version_compare(JVERSION, '2.5.10', 'ge') and version_compare(JVERSION, '3.0', 'lt')) {
             return;
         }
         // Display attachments lists for category descriptions
         $parent_entity = 'category';
         // Add the refresh Javascript
         $uri = JFactory::getURI();
         $base_url = $uri->root(true);
         $doc = JFactory::getDocument();
         // Allow remapping of parent ID (eg, for Joomfish)
         if (jimport('attachments_remapper.remapper')) {
             $parent_id = AttachmentsRemapper::remapParentID($parent_id, $parent_type, $parent_entity);
         }
         // Figure out if the attachments list should be visible for this category
         jimport('joomla.application.component.helper');
         $params = JComponentHelper::getParams('com_attachments');
         $always_show_category_attachments = $params->get('always_show_category_attachments', false);
         $all_but_article_views = $params->get('hide_except_article_views', false);
         if ($all_but_article_views && !$always_show_category_attachments) {
             return;
         }
         // Construct the attachment list
         $Itemid = JRequest::getInt('Itemid', 1);
         $from = 'frontpage';
         $user_can_add = $parent->userMayAddAttachment($parent_id, $parent_entity);
         $attachments = AttachmentsHelper::attachmentsListHTML($parent_id, $parent_type, $parent_entity, $user_can_add, $Itemid, $from, true, $user_can_add);
         // If the attachments list is empty, insert an empty div for it
         if ($attachments == '') {
             jimport('joomla.application.component.helper');
             $class_name = $params->get('attachments_table_style', 'attachmentsList');
             $div_id = 'attachmentsList' . '_' . $parent_type . '_' . $parent_entity . '_' . (string) $parent_id;
             $attachments = "\n<div class=\"{$class_name}\" id=\"{$div_id}\"></div>\n";
         }
         // Insert the attachments after the category description
         $reptag = '<div class="clr"></div>';
         $body = JResponse::getBody();
         $body = str_replace($reptag, $attachments . $reptag, $body);
         JResponse::setBody($body);
     }
 }
Beispiel #7
0
 /**
  * The content plugin that inserts the attachments list into content items
  *
  * @param	string	 $context  the context of the content being passed to the plugin.
  * @param	&object	 &$row	   the content object (eg, article) being displayed
  * @param	&object	 &$params  the parameters
  * @param	int		 $page	   the 'page' number
  *
  * @return true if anything has been inserted into the content object
  */
 public function onContentBeforeDisplay($context, &$row, &$params, $page = 0)
 {
     $view = JRequest::getCmd('view');
     $layout = JRequest::getCmd('layout');
     if ($context == 'com_content.category' and $view == 'category' and $layout == 'blog') {
         // Use onContentPrepare for category blog articles for Joomla 3.4+
         if (version_compare(JVERSION, '3.4', 'ge')) {
             return false;
         }
     }
     // Set the parent info from the context
     if (strpos($context, '.') === false) {
         // Assume the context is the parent_type
         $parent_type = $context;
         $parent_entity = '';
     } else {
         list($parent_type, $parent_entity) = explode('.', $context, 2);
     }
     // ??? Do we need to filter to ensure only articles use this callback?
     // Load the language
     $lang = JFactory::getLanguage();
     $lang->load('plg_content_attachments', dirname(__FILE__));
     // Add the refresh javascript
     AttachmentsJavascript::setupJavascript();
     // Always include the hide rule (since it may be needed to hide the custom tags)
     JHtml::stylesheet('com_attachments/attachments_hide.css', array(), true);
     // Get the article/parent handler
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     if (!$apm->attachmentsPluginInstalled($parent_type)) {
         // Exit quietly if there is no Attachments plugin to handle this parent_type
         return false;
     }
     $parent = $apm->getAttachmentsPlugin($parent_type);
     // If this attachments plugin is disabled, skip it
     if (!$apm->attachmentsPluginEnabled($parent_type)) {
         return false;
     }
     // Figure out the parent entity
     $parent_entity = $parent->determineParentEntity($row);
     if (!$parent_entity) {
         return false;
     }
     // Get the parent ID
     $parent_id = null;
     if (isset($row->id) && $row->id > 0) {
         $parent_id = (int) $row->id;
     } else {
         $parent_id = $parent->getParentId($row);
     }
     // Exit if there is no parent
     if ($parent_id === false) {
         return false;
     }
     // Allow remapping of parent ID (eg, for Joomfish)
     if (jimport('attachments_remapper.remapper')) {
         $parent_id = AttachmentsRemapper::remapParentID($parent_id, $parent_type, $parent_entity);
     }
     // Exit if we should not display attachments for this parent
     if ($parent->attachmentsHiddenForParent($row, $parent_id, $parent_entity)) {
         return false;
     }
     // Add the attachments list
     $parent->insertAttachmentsList($row, $parent_id, $parent_entity);
     // ??? if (isset($row->text)) $row->text .= " [OCBD text $context]";
     // ??? if (isset($row->introtext)) $row->introtext .= " [OCBD introtext $context]";
     return;
 }
Beispiel #8
0
 /**
  * Save an attachment (from editing)
  */
 public function save($key = null, $urlVar = null)
 {
     // Check for request forgeries
     JSession::checkToken() or die(JText::_('JINVALID_TOKEN'));
     // Access check.
     $user = JFactory::getUser();
     if (!($user->authorise('core.edit', 'com_attachments') or $user->authorise('core.edit.own', 'com_attachments'))) {
         return JError::raiseError(403, JText::_('JERROR_ALERTNOAUTHOR') . ' (ERR 134)');
     }
     $model = $this->getModel();
     $attachment = $model->getTable();
     // Make sure the article ID is valid
     $attachment_id = JRequest::getInt('id');
     if (!$attachment->load($attachment_id)) {
         $errmsg = JText::sprintf('ATTACH_ERROR_CANNOT_UPDATE_ATTACHMENT_INVALID_ID_N', $id) . ' (ERR 135)';
         JError::raiseError(500, $errmsg);
     }
     // Note the old uri type
     $old_uri_type = $attachment->uri_type;
     // Get the data from the form
     if (!$attachment->bind(JRequest::get('post'))) {
         $errmsg = $attachment->getError() . ' (ERR 136)';
         JError::raiseError(500, $errmsg);
     }
     // Get the parent handler for this attachment
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     if (!$apm->attachmentsPluginInstalled($attachment->parent_type)) {
         $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $attachment->parent_type) . ' (ERR 135B)';
         JError::raiseError(500, $errmsg);
     }
     $parent = $apm->getAttachmentsPlugin($attachment->parent_type);
     // See if the parent ID has been changed
     $parent_changed = false;
     $old_parent_id = JRequest::getString('old_parent_id');
     if ($old_parent_id == '') {
         $old_parent_id = null;
     } else {
         $old_parent_id = JRequest::getInt('old_parent_id');
     }
     // Handle new parents (in process of creation)
     if ($parent->newParent($attachment)) {
         $attachment->parent_id = null;
     }
     // Deal with updating an orphaned attachment
     if ($old_parent_id == null && is_numeric($attachment->parent_id)) {
         $parent_changed = true;
     }
     // Check for normal parent changes
     if ($old_parent_id && $attachment->parent_id != $old_parent_id) {
         $parent_changed = true;
     }
     // See if we are updating a file or URL
     $new_uri_type = JRequest::getWord('update');
     if ($new_uri_type && !in_array($new_uri_type, AttachmentsDefines::$LEGAL_URI_TYPES)) {
         // Make sure only legal values are entered
         $new_uri_type = '';
     }
     // See if the parent type has changed
     $new_parent_type = JRequest::getCmd('new_parent_type');
     $new_parent_entity = JRequest::getCmd('new_parent_entity');
     $old_parent_type = JRequest::getCmd('old_parent_type');
     $old_parent_entity = JRequest::getCmd('old_parent_entity');
     if ($new_parent_type && ($new_parent_type != $old_parent_type || $new_parent_entity != $old_parent_entity)) {
         $parent_changed = true;
     }
     // If the parent has changed, make sure they have selected the new parent
     if ($parent_changed && (int) $attachment->parent_id == -1) {
         $errmsg = JText::sprintf('ATTACH_ERROR_MUST_SELECT_PARENT');
         echo "<script type=\"text/javascript\"> alert('{$errmsg}'); window.history.go(-1); </script>\n";
         exit;
     }
     // If the parent has changed, switch the parent, rename files if necessary
     if ($parent_changed) {
         if ($new_uri_type == 'url' && $old_uri_type == 'file') {
             // If we are changing parents and converting from file to URL, delete the old file
             jimport('joomla.filesystem.file');
             // Load the attachment so we can get its filename_sys
             $db = JFactory::getDBO();
             $query = $db->getQuery(true);
             $query->select('filename_sys, id')->from('#__attachments')->where('id=' . (int) $attachment->id);
             $db->setQuery($query, 0, 1);
             $filename_sys = $db->loadResult();
             JFile::delete($filename_sys);
             AttachmentsHelper::clean_directory($filename_sys);
         } else {
             // Otherwise switch the file/url to the new parent
             if ($old_parent_id == null) {
                 $old_parent_id = 0;
                 // NOTE: When attaching a file to an article during creation,
                 //		 the article_id (parent_id) is initially null until
                 //		 the article is saved (at that point the
                 //		 parent_id/article_id updated).	 If the attachment is
                 //		 added and creating the article is canceled, the
                 //		 attachment exists but is orhpaned since it does not
                 //		 have a parent.	 It's article_id is null, but it is
                 //		 saved in directory as if its article_id is 0:
                 //		 article/0/file.txt.  Therefore, if the parent has
                 //		 changed, we pretend the old_parent_id=0 for file
                 //		 renaming/moving.
             }
             $error_msg = AttachmentsHelper::switch_parent($attachment, $old_parent_id, $attachment->parent_id, $new_parent_type, $new_parent_entity);
             if ($error_msg != '') {
                 $errmsg = JText::_($error_msg) . ' (ERR 137)';
                 $link = 'index.php?option=com_attachments';
                 $this->setRedirect($link, $errmsg, 'error');
                 return;
             }
         }
     }
     // Update parent type/entity, if needed
     if ($new_parent_type && $new_parent_type != $old_parent_type) {
         $attachment->parent_type = $new_parent_type;
     }
     if ($new_parent_type && $new_parent_entity != $old_parent_entity) {
         $attachment->parent_entity = $new_parent_entity;
     }
     // Get the article/parent handler
     if ($new_parent_type) {
         $parent_type = $new_parent_type;
         $parent_entity = $new_parent_entity;
     } else {
         $parent_type = JRequest::getCmd('parent_type', 'com_content');
         $parent_entity = JRequest::getCmd('parent_entity', 'default');
     }
     $parent = $apm->getAttachmentsPlugin($parent_type);
     $parent_entity = $parent->getCanonicalEntityId($parent_entity);
     // Get the title of the article/parent
     $new_parent = JRequest::getBool('new_parent', false);
     $parent->new = $new_parent;
     if ($new_parent) {
         $attachment->parent_id = null;
         $parent->title = '';
     } else {
         $parent->title = $parent->getTitle($attachment->parent_id, $parent_entity);
     }
     // Check to make sure the user has permissions to edit the attachment
     if (!$parent->userMayEditAttachment($attachment)) {
         // ??? Add better error message
         return JError::raiseError(403, JText::_('JERROR_ALERTNOAUTHOR') . ' (ERR 139)');
     }
     // Double-check to see if the URL changed
     $old_url = JRequest::getString('old_url');
     if (!$new_uri_type && $old_url && $old_url != $attachment->url) {
         $new_uri_type = 'url';
     }
     // If this is a URL, get settings
     $verify_url = false;
     $relative_url = false;
     if ($new_uri_type == 'url') {
         // See if we need to verify the URL (if applicable)
         if (JRequest::getWord('verify_url') == 'verify') {
             $verify_url = true;
         }
         // Allow relative URLs?
         if (JRequest::getWord('url_relative') == 'relative') {
             $relative_url = true;
         }
     }
     // Compute the update time
     $now = JFactory::getDate();
     // Update create/modify info
     $attachment->modified_by = $user->get('id');
     $attachment->modified = $now->toSql();
     // Upload new file/url and create/update the attachment
     $msg = null;
     $msgType = 'message';
     if ($new_uri_type == 'file') {
         // Upload a new file
         $result = AttachmentsHelper::upload_file($attachment, $parent, $attachment_id, 'update');
         if (is_object($result)) {
             $msg = $result->error_msg . ' (ERR 140)';
             $msgType = 'error';
         } else {
             $msg = $result;
         }
         // NOTE: store() is not needed if upload_file() is called since it does it
     } elseif ($new_uri_type == 'url') {
         // Upload/add the new URL
         $result = AttachmentsHelper::add_url($attachment, $parent, $verify_url, $relative_url, $old_uri_type, $attachment_id);
         // NOTE: store() is not needed if add_url() is called since it does it
         if (is_object($result)) {
             $msg = $result->error_msg . ' (ERR 141)';
             $msgType = 'error';
         } else {
             $msg = $result;
         }
     } else {
         // Extra handling for checkboxes for URLs
         if ($attachment->uri_type == 'url') {
             // Update the url_relative field
             $attachment->url_relative = $relative_url;
             $attachment->url_verify = $verify_url;
         }
         // Remove any extraneous fields
         if (isset($attachment->parent_entity_name)) {
             unset($attachment->parent_entity_name);
         }
         // Save the updated attachment info
         if (!$attachment->store()) {
             $errmsg = $attachment->getError() . ' (ERR 142)';
             JError::raiseError(500, $errmsg);
         }
     }
     switch ($this->getTask()) {
         case 'apply':
             if (!$msg) {
                 $msg = JText::_('ATTACH_CHANGES_TO_ATTACHMENT_SAVED');
             }
             $link = 'index.php?option=com_attachments&task=attachment.edit&cid[]=' . (int) $attachment->id;
             break;
         case 'save':
         default:
             if (!$msg) {
                 $msg = JText::_('ATTACH_ATTACHMENT_UPDATED');
             }
             $link = 'index.php?option=com_attachments';
             break;
     }
     // If invoked from an iframe popup, close it and refresh the attachments list
     $from = JRequest::getWord('from');
     $known_froms = $parent->knownFroms();
     if (in_array($from, $known_froms)) {
         // If there has been a problem, alert the user and redisplay
         if ($msgType == 'error') {
             $errmsg = $msg;
             if (DIRECTORY_SEPARATOR == "\\") {
                 // Fix filename on Windows system so alert can display it
                 $errmsg = str_replace(DIRECTORY_SEPARATOR, "\\\\", $errmsg);
             }
             $errmsg = str_replace("'", "\\'", $errmsg);
             $errmsg = str_replace("<br />", "\\n", $errmsg);
             echo "<script type=\"text/javascript\"> alert('{$errmsg}');  window.history.go(-1); </script>";
             exit;
         }
         // Can only refresh the old parent
         if ($parent_changed) {
             $parent_type = $old_parent_type;
             $parent_entity = $old_parent_entity;
             $parent_id = $old_parent_id;
         } else {
             $parent_id = (int) $attachment->parent_id;
         }
         // Close the iframe and refresh the attachments list in the parent window
         $uri = JFactory::getURI();
         $base_url = $uri->base(true);
         $lang = JRequest::getCmd('lang', '');
         AttachmentsJavascript::closeIframeRefreshAttachments($base_url, $parent_type, $parent_entity, $parent_id, $lang, $from);
         exit;
     }
     $this->setRedirect($link, $msg, $msgType);
 }
Beispiel #9
0
 /**
  * Attachments Search method
  *
  * The sql must return the following fields that are
  * used in a common display routine: href, title, section, created, text,
  * browsernav
  * @param string Target search string
  * @param string mathcing option, exact|any|all
  * @param string ordering option, newest|oldest|popular|alpha|category
  * @param mixed An array if restricted to areas, null if search all
  */
 public function onContentSearch($text, $phrase = '', $ordering = '', $areas = null)
 {
     $user = JFactory::getUser();
     // Exit if the search does not include attachments
     if (is_array($areas)) {
         if (!array_intersect($areas, array_keys($this->onContentSearchAreas()))) {
             return array();
         }
     }
     // Make sure we have something to search for
     $text = JString::trim($text);
     if ($text == '') {
         return array();
     }
     // load search limit from plugin params
     $limit = $this->params->def('search_limit', 50);
     // Get the component parameters
     jimport('joomla.application.component.helper');
     $attachParams = JComponentHelper::getParams('com_attachments');
     $secure = $attachParams->get('secure', false);
     $user_field_1 = false;
     if (JString::strlen($attachParams->get('user_field_1_name', '')) > 0) {
         $user_field_1 = true;
         $user_field_1_name = $attachParams->get('user_field_1_name');
     }
     $user_field_2 = false;
     if (JString::strlen($attachParams->get('user_field_2_name', '')) > 0) {
         $user_field_2 = true;
         $user_field_2_name = $attachParams->get('user_field_2_name');
     }
     $user_field_3 = false;
     if (JString::strlen($attachParams->get('user_field_3_name', '')) > 0) {
         $user_field_3 = true;
         $user_field_3_name = $attachParams->get('user_field_3_name');
     }
     $wheres = array();
     // Create the search query
     $db = JFactory::getDBO();
     switch ($phrase) {
         case 'exact':
             $text = $db->quote('%' . $db->escape($text, true) . '%', false);
             $user_fields_sql = '';
             if ($user_field_1) {
                 $user_fields_sql .= " OR (LOWER(a.user_field_1) LIKE {$text})";
             }
             if ($user_field_2) {
                 $user_fields_sql .= " OR (LOWER(a.user_field_2) LIKE {$text})";
             }
             if ($user_field_3) {
                 $user_fields_sql .= " OR (LOWER(a.user_field_3) LIKE {$text})";
             }
             $where = "((LOWER(a.filename) LIKE {$text})" . " OR (LOWER(a.display_name) LIKE {$text})" . $user_fields_sql . " OR (LOWER(a.description) LIKE {$text}))";
             break;
         default:
             $words = explode(' ', $text);
             $wheres = array();
             foreach ($words as $word) {
                 $word = $db->quote('%' . $db->escape($word, true) . '%', false);
                 $wheres2 = array();
                 $wheres2[] = "LOWER(a.filename) LIKE {$word}";
                 $wheres2[] = "LOWER(a.display_name) LIKE {$word}";
                 $wheres2[] = "LOWER(a.url) LIKE {$word}";
                 if ($user_field_1) {
                     $wheres2[] = "LOWER(a.user_field_1) LIKE {$word}";
                 }
                 if ($user_field_2) {
                     $wheres2[] = "LOWER(a.user_field_2) LIKE {$word}";
                 }
                 if ($user_field_3) {
                     $wheres2[] = "LOWER(a.user_field_3) LIKE {$word}";
                 }
                 $wheres2[] = "LOWER(a.description) LIKE {$word}";
                 $wheres[] = implode(' OR ', $wheres2);
             }
             $where = '(' . implode($phrase == 'all' ? ') AND (' : ') OR (', $wheres) . ')';
             break;
     }
     // Set up the sorting
     switch ($ordering) {
         case 'oldest':
             $order = 'a.created ASC';
             break;
         case 'newest':
             $order = 'a.created DESC';
             break;
         case 'alpha':
         default:
             $order = 'a.filename DESC';
     }
     // Load the permissions functions
     $user = JFactory::getUser();
     $user_levels = implode(',', array_unique($user->getAuthorisedViewLevels()));
     // Construct and execute the query
     $query = $db->getQuery(true);
     $query->select('*')->from('#__attachments AS a');
     $query->where("( {$where} ) AND a.state = 1");
     if (!$user->authorise('core.admin')) {
         $query->where('a.access in (' . $user_levels . ')');
     }
     $query->order($order);
     $db->setQuery($query, 0, $limit);
     $attachments = $db->loadObjectList();
     $count = count($attachments);
     // See if we are done
     $results = array();
     if ($count <= 0) {
         return $results;
     }
     // Prepare to get parent info
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     // Add the result data to the results of the search
     $k = 0;
     for ($i = 0; $i < $count; $i++) {
         $attachment = $attachments[$i];
         // Get the parent handler
         $parent_type = $attachment->parent_type;
         $parent_entity = $attachment->parent_entity;
         if (!$apm->attachmentsPluginInstalled($parent_type)) {
             // Exit if there is no Attachments plugin to handle this parent_type, ignore it
             continue;
         }
         $parent = $apm->getAttachmentsPlugin($parent_type);
         // Ignore the attachment if the user may not see the parent
         if (!$parent->userMayViewParent($attachment->parent_id, $parent_entity)) {
             continue;
         }
         // Ignore the attachment if the parent is not published
         if (!$parent->isParentPublished($attachment->parent_id, $parent_entity)) {
             continue;
         }
         // Do not add the attachment if the user may not access it
         if (!$parent->userMayAccessAttachment($attachment)) {
             continue;
         }
         // Add the parent title
         $attachment->parent_title = $parent->getTitle($attachment->parent_id, $parent_entity);
         // Construct the download URL if necessary
         if ($secure && $attachment->uri_type == 'file') {
             $attachment->href = JRoute::_("index.php?option=com_attachments&task=download&id=" . (int) $attachment->id);
         } else {
             $attachment->href = $attachment->url;
         }
         if ($attachment->display_name && JString::strlen($attachment->display_name) > 0) {
             $attachment->title = JString::str_ireplace('&#183;', '.', $attachment->display_name);
         } else {
             if ($attachment->uri_type == 'file') {
                 $attachment->title = $attachment->filename;
             } else {
                 $attachment->title = $attachment->url;
             }
         }
         // Set the text to the string containing the search target
         if (JString::strlen($attachment->display_name) > 0) {
             $text = $attachment->display_name . " (" . JText::_('ATTACH_FILENAME_COLON') . " " . $attachment->filename . ") ";
         } else {
             $text = JText::_('ATTACH_FILENAME_COLON') . " " . $attachment->filename;
         }
         if (JString::strlen($attachment->description) > 0) {
             $text .= " | " . JText::_('ATTACH_DESCRIPTION_COLON') . stripslashes($attachment->description);
         }
         if ($user_field_1 && JString::strlen($attachment->user_field_1) > 0) {
             $text .= " | " . $user_field_1_name . ": " . stripslashes($attachment->user_field_1);
         }
         if ($user_field_2 && JString::strlen($attachment->user_field_2) > 0) {
             $text .= " | " . $user_field_2_name . ": " . stripslashes($attachment->user_field_2);
         }
         if ($user_field_3 && JString::strlen($attachment->user_field_3) > 0) {
             $text .= " | " . $user_field_3_name . ": " . stripslashes($attachment->user_field_3);
         }
         $attachment->text = $text;
         $attachment->browsernav = 2;
         $parent_entity_name = JText::_('ATTACH_' . $parent_entity);
         $attachment->parent_entity_name = $parent_entity_name;
         $parent_title = JText::_($parent->getTitle($attachment->parent_id, $parent_entity));
         $attachment->section = JText::sprintf('ATTACH_ATTACHED_TO_PARENT_S_TITLE_S', $parent_entity_name, $parent_title);
         $results[$k] = $attachment;
         $k++;
     }
     return $results;
 }
 /**
  * Insert attachments token button
  *
  * @param string $name The name of the editor form
  * @param int $asset The asset ID for the entity being edited
  * @param int $authro The ID of the author of the entity
  *
  * @return a button
  */
 public function onDisplay($name, $asset, $author)
 {
     // Get the component parameters
     jimport('joomla.application.component.helper');
     $params = JComponentHelper::getParams('com_attachments');
     // This button should only be displayed in 'custom placement' mode.
     // Check to make sure that is the case
     $placement = $params->get('attachments_placement', 'end');
     if ($placement != 'custom') {
         return false;
     }
     // Avoid displaying the button for anything except for registered parents
     $parent_type = JRequest::getCmd('option');
     // Handle sections and categories specially (since they are really com_content)
     if ($parent_type == 'com_categories') {
         $parent_type = 'com_content';
     }
     // Get the article/parent handler
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     if (!$apm->attachmentsPluginInstalled($parent_type)) {
         // Exit if there is no Attachments plugin to handle this parent_type
         return new JObject();
     }
     // Get ready for language things
     $lang = JFactory::getLanguage();
     if (!$lang->load('plg_editors-xtd_insert_attachments_token', dirname(__FILE__))) {
         // If the desired translation is not available, at least load the English
         $lang->load('plg_editors-xtd_insert_attachments_token', JPATH_ADMINISTRATOR, 'en-GB');
     }
     // Set up the Javascript to insert the tag
     $getContent = $this->_subject->getContent($name);
     $present = JText::_('ATTACH_ATTACHMENTS_TOKEN_ALREADY_PRESENT', true);
     $js = "\n\t\t\tfunction insertAttachmentsToken(editor) {\n\t\t\t\tvar content = {$getContent}\n\t\t\t\tif (content.match(/\\{\\s*attachments/i)) {\n\t\t\t\t\talert('{$present}');\n\t\t\t\t\treturn false;\n\t\t\t\t} else {\n\t\t\t\t\tjInsertEditorText('<span class=\"hide_attachments_token\">{attachments}</span>', editor);\n\t\t\t\t}\n\t\t\t}\n\t\t\t";
     $app = JFactory::getApplication();
     $doc = JFactory::getDocument();
     $uri = JFactory::getURI();
     $doc->addScriptDeclaration($js);
     // Add the regular css file
     JHtml::stylesheet('com_attachments/attachments_list.css', array(), true);
     JHtml::stylesheet('com_attachments/insert_attachments_token_button.css', array(), true);
     // Handle RTL styling (if necessary)
     if ($lang->isRTL()) {
         JHtml::stylesheet('com_attachments/attachments_list_rtl.css', array(), true);
         JHtml::stylesheet('com_attachments/insert_attachments_token_button_rtl.css', array(), true);
     }
     $button = new JObject();
     $button->set('modal', false);
     $button->set('class', 'btn');
     $button->set('onclick', 'insertAttachmentsToken(\'' . $name . '\');return false;');
     $button->set('text', JText::_('ATTACH_ATTACHMENTS_TOKEN'));
     $button->set('title', JText::_('ATTACH_ATTACHMENTS_TOKEN_DESCRIPTION'));
     if ($app->isAdmin()) {
         $button_name = 'insert_attachments_token';
         if (version_compare(JVERSION, '3.3', 'ge')) {
             $button_name = 'paperclip';
         }
         $button->set('name', $button_name);
     } else {
         $button_name = 'insert_attachments_token_frontend';
         if (version_compare(JVERSION, '3.3', 'ge')) {
             $button_name = 'paperclip';
         }
         $button->set('name', $button_name);
     }
     // TODO: The button writer needs to take into account the javascript directive
     // $button->set('link', 'javascript:void(0)');
     $button->set('link', '#');
     return $button;
 }
 /**
  * Return the list of installed parent entities
  *
  * @return array of entity info (see var $_entity_info definition above)
  */
 public function &getInstalledEntityInfo()
 {
     if (count($this->entity_info) == 0) {
         // Add an option for each entity
         JPluginHelper::importPlugin('attachments');
         $apm = getAttachmentsPluginManager();
         // Process all the parent types
         foreach ($this->parent_types as $parent_type) {
             $parent = $apm->getAttachmentsPlugin($parent_type);
             $entities = $parent->getEntities();
             // Process each entity for this parent type
             foreach ($entities as $entity) {
                 $centity = $parent->getCanonicalEntityId($entity);
                 $this->entity_info[] = array('id' => $centity, 'name' => JText::_('ATTACH_' . $centity), 'name_plural' => JText::_('ATTACH_' . $centity . 's'), 'parent_type' => $parent_type);
             }
         }
     }
     return $this->entity_info;
 }
Beispiel #12
0
 /**
  * Switch attachment from one parent to another
  *
  * @param &object &$attachment the attachment object
  * @param int $old_parent_id the id for the old parent
  * @param int $new_parent_id the id for the new parent
  * @param string $new_parent_type the new parent type (eg, 'com_content')
  * @param string $new_parent_entity the new parent entity (eg, 'category')
  *
  * @return '' if successful, else an error message
  */
 public static function switch_parent(&$attachment, $old_parent_id, $new_parent_id, $new_parent_type = null, $new_parent_entity = null)
 {
     // Switch the parent as specified, renaming the file as necessary
     // Return success status
     if ($attachment->uri_type == 'url') {
         // Do not need to do any file operations if this is a URL
         return '';
     }
     // Get the article/parent handler
     if ($new_parent_type) {
         $parent_type = $new_parent_type;
         $parent_entity = $new_parent_entity;
     } else {
         $parent_type = $attachment->parent_type;
         $parent_entity = $attachment->parent_entity;
     }
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     if (!$apm->attachmentsPluginInstalled($parent_type)) {
         $errmsg = JText::sprintf('ATTACH_ERROR_UNKNOWN_PARENT_TYPE_S', $parent_type) . ' (ERR 45)';
         JError::raiseError(500, $errmsg);
     }
     $parent = $apm->getAttachmentsPlugin($parent_type);
     // Set up the entity name for display
     $parent_entity = $parent->getCanonicalEntityId($parent_entity);
     $parent_entity_name = JText::_('ATTACH_' . $parent_entity);
     // Get the component parameters
     jimport('joomla.application.component.helper');
     $params = JComponentHelper::getParams('com_attachments');
     // Define where the attachments move to
     $upload_url = AttachmentsDefines::$ATTACHMENTS_SUBDIR;
     $upload_dir = JPATH_SITE . '/' . $upload_url;
     // Figure out the new system filename
     $new_path = $parent->getAttachmentPath($parent_entity, $new_parent_id, null);
     $new_fullpath = $upload_dir . '/' . $new_path;
     // Make sure the new directory exists
     jimport('joomla.filesystem.folder');
     if (!JFolder::create($new_fullpath)) {
         $errmsg = JText::sprintf('ATTACH_ERROR_UNABLE_TO_CREATE_DIR_S', $new_fullpath) . ' (ERR 46)';
         JError::raiseError(500, $errmsg);
     }
     // Construct the new filename and URL
     $old_filename_sys = $attachment->filename_sys;
     $new_filename_sys = $new_fullpath . $attachment->filename;
     $new_url = JString::str_ireplace(DIRECTORY_SEPARATOR, '/', $upload_url . '/' . $new_path . $attachment->filename);
     // Rename the file
     jimport('joomla.filesystem.file');
     if (JFile::exists($new_filename_sys)) {
         return JText::sprintf('ATTACH_ERROR_CANNOT_SWITCH_PARENT_S_NEW_FILE_S_ALREADY_EXISTS', $parent_entity_name, $attachment->filename);
     }
     if (!JFile::move($old_filename_sys, $new_filename_sys)) {
         $new_filename = $new_path . $attachment->filename;
         return JText::sprintf('ATTACH_ERROR_CANNOT_SWITCH_PARENT_S_RENAMING_FILE_S_FAILED', $parent_entity_name, $new_filename);
     }
     AttachmentsHelper::write_empty_index_html($new_fullpath);
     // Save the changes to the attachment record immediately
     $attachment->parent_id = $new_parent_id;
     $attachment->parent_entity = $parent_entity;
     $attachment->parent_entity_name = $parent_entity_name;
     $attachment->filename_sys = $new_filename_sys;
     $attachment->url = $new_url;
     // Clean up after ourselves
     AttachmentsHelper::clean_directory($old_filename_sys);
     return '';
 }
 /**
  * Add Attachment button
  *
  * @param string $name The name of the editor form
  * @param int $asset The asset ID for the entity being edited
  * @param int $authro The ID of the author of the entity
  *
  * @return a button
  */
 public function onDisplay($name, $asset, $author)
 {
     $app = JFactory::getApplication();
     // Avoid displaying the button for anything except for registered parents
     $parent_type = JRequest::getCmd('option');
     if (!$parent_type) {
         return;
     }
     $parent_entity = 'default';
     $editor = 'article';
     // Handle categories specially (since they are really com_content)
     if ($parent_type == 'com_categories') {
         $parent_type = 'com_content';
         $parent_entity = 'category';
         $editor = 'category';
     }
     // Get the parent ID (id or first of cid array)
     //	   NOTE: $parent_id=0 means no id (usually means creating a new entity)
     $cid = JRequest::getVar('cid', array(0), '', 'array');
     $parent_id = 0;
     if (count($cid) > 0) {
         $parent_id = (int) $cid[0];
     }
     if ($parent_id == 0) {
         $a_id = JRequest::getInt('a_id');
         if (!is_null($a_id)) {
             $parent_id = (int) $a_id;
         }
     }
     if ($parent_id == 0) {
         $nid = JRequest::getInt('id');
         if (!is_null($nid)) {
             $parent_id = (int) $nid;
         }
     }
     // Check for the special case where we are creating an article from a category list
     $item_id = JRequest::getInt('Itemid');
     $menu = $app->getMenu();
     $menu_item = $menu->getItem($item_id);
     if ($menu_item and $menu_item->query['view'] == 'category' and empty($a_id)) {
         $parent_entity = 'article';
         $parent_id = NULL;
     }
     // Get the article/parent handler
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     if (!$apm->attachmentsPluginInstalled($parent_type)) {
         // Exit if there is no Attachments plugin to handle this parent_type
         return new JObject();
     }
     // Figure out where we are and construct the right link and set
     $uri = JFactory::getURI();
     $base_url = $uri->root(true);
     if ($app->isAdmin()) {
         $base_url = str_replace('/administrator', '', $base_url);
     }
     // Set up the Javascript framework
     require_once JPATH_SITE . '/components/com_attachments/javascript.php';
     AttachmentsJavascript::setupJavascript();
     // Get the parent handler
     $parent = $apm->getAttachmentsPlugin($parent_type);
     $parent_entity = $parent->getCanonicalEntityId($parent_entity);
     if ($parent_id == 0) {
         # Last chance to get the id in extension editors
         $view = JRequest::getWord('view');
         $layout = JRequest::getWord('layout');
         $parent_id = $parent->getParentIdInEditor($parent_entity, $view, $layout);
     }
     // Make sure we have permissions to add attachments to this article or category
     if (!$parent->userMayAddAttachment($parent_id, $parent_entity, $parent_id == 0)) {
         return;
     }
     // Allow remapping of parent ID (eg, for Joomfish)
     if (jimport('attachments_remapper.remapper')) {
         $parent_id = AttachmentsRemapper::remapParentID($parent_id, $parent_type, $parent_entity);
     }
     // Add the regular css file
     JHtml::stylesheet('com_attachments/attachments_list.css', array(), true);
     JHtml::stylesheet('com_attachments/add_attachment_button.css', array(), true);
     // Handle RTL styling (if necessary)
     $lang = JFactory::getLanguage();
     if ($lang->isRTL()) {
         JHtml::stylesheet('com_attachments/attachments_list_rtl.css', array(), true);
         JHtml::stylesheet('com_attachments/add_attachment_button_rtl.css', array(), true);
     }
     // Load the language file from the frontend
     $lang->load('com_attachments', dirname(__FILE__));
     // Create the [Add Attachment] button object
     $button = new JObject();
     $link = $parent->getEntityAddUrl($parent_id, $parent_entity, 'closeme');
     $link .= '&amp;editor=' . $editor;
     // Finalize the [Add Attachment] button info
     $button->set('modal', true);
     $button->set('class', 'btn');
     $button->set('text', JText::_('ATTACH_ADD_ATTACHMENT'));
     if ($app->isAdmin()) {
         $button_name = 'add_attachment';
         if (version_compare(JVERSION, '3.3', 'ge')) {
             $button_name = 'paperclip';
         }
         $button->set('name', $button_name);
     } else {
         // Needed for Joomal 2.5
         $button_name = 'add_attachment_frontend';
         if (version_compare(JVERSION, '3.3', 'ge')) {
             $button_name = 'paperclip';
         }
         $button->set('name', $button_name);
     }
     $button->set('link', $link);
     $button->set('options', "{handler: 'iframe', size: {x: 920, y: 530}}");
     return $button;
 }
Beispiel #14
0
 /**
  * Regenerate the system filenames for all attachments.
  *
  * This function may need to run if the admin has moved the attachments
  * from one computer to another and the actual file paths need to be
  * updated.
  */
 public static function regenerate_system_filenames()
 {
     require_once JPATH_SITE . '/components/com_attachments/helper.php';
     // Get the component parameters
     jimport('joomla.application.component.helper');
     $params = JComponentHelper::getParams('com_attachments');
     // Define where the attachments go
     $upload_url = AttachmentsDefines::$ATTACHMENTS_SUBDIR;
     $upload_dir = JPATH_SITE . '/' . $upload_url;
     // Get all the attachment IDs
     $db = JFactory::getDBO();
     $query = $db->getQuery(true);
     $query->select('id')->from('#__attachments')->where('uri_type=' . $db->quote('file'));
     $db->setQuery($query);
     $attachments = $db->loadObjectList();
     if ($db->getErrorNum()) {
         $errmsg = $db->stderr() . ' (ERR 72)';
         JError::raiseError(500, $errmsg);
     }
     if (count($attachments) == 0) {
         return JText::_('ATTACH_NO_ATTACHMENTS_WITH_FILES');
     }
     $IDs = array();
     foreach ($attachments as $attachment) {
         $IDs[] = $attachment->id;
     }
     // Get the parent plugin manager
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     // Update the system filenames for all the attachments
     jimport('joomla.filesystem.file');
     jimport('joomla.filesystem.folder');
     JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_attachments/tables');
     $attachment = JTable::getInstance('Attachment', 'AttachmentsTable');
     $msg = '';
     $numUpdated = 0;
     $numMissing = 0;
     foreach ($IDs as $id) {
         $attachment->load($id);
         // Get the actual parent id for this attachment
         // (Needed because orphaned parent_id is null, which the Table loads as 1)
         $query = $db->getQuery(true);
         $query->select('parent_id')->from('#__attachments')->where('id = ' . (int) $id);
         $db->setQuery($query, 0, 1);
         $parent_id = $db->loadResult();
         if ($db->getErrorNum()) {
             $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_S_ID_N', $attachment->parent_entity, $parent_id) . ' (ERR 73)';
             JError::raiseError(500, $errmsg);
         }
         // Construct the updated system filename
         $old_filename_sys = $attachment->filename_sys;
         // Get info about the system filename
         $finfo = AttachmentsUpdate::checkFilename($old_filename_sys);
         $basename = $finfo->basename;
         // Reconstruct the current system filename (in case of migrations)
         $current_filename_sys = JPATH_SITE . '/' . $finfo->relfile;
         // Get the parent object
         $parent = $apm->getAttachmentsPlugin($attachment->parent_type);
         if (!JFile::exists($current_filename_sys)) {
             $msg .= JText::sprintf('ATTACH_ERROR_MISSING_ATTACHMENT_FILE_S', $current_filename_sys) . "<br/>";
             $numMissing++;
         } elseif (!is_numeric($parent_id) || !$parent->parentExists($attachment->parent_id, $attachment->parent_entity)) {
             $msg .= JText::sprintf('ATTACH_ERROR_MISSING_PARENT_FOR_ATTACHMENT_S', $current_filename_sys) . "<br/>";
             $numMissing++;
         } else {
             // Construct the new system filename and url (based on entities, etc)
             $newdir = $parent->getAttachmentPath($attachment->parent_entity, $attachment->parent_id, null);
             $new_path = $upload_dir . '/' . $newdir;
             if ($finfo->oldstyle && $finfo->prefix) {
                 $new_filename_sys = $new_path . $finfo->basename_no_prefix;
                 $attachment->filename = $finfo->basename_no_prefix;
                 $new_url = str_replace(DIRECTORY_SEPARATOR, '/', $upload_url . '/' . $newdir . $finfo->basename_no_prefix);
             } else {
                 $new_filename_sys = $new_path . $basename;
                 $new_url = str_replace(DIRECTORY_SEPARATOR, '/', $upload_url . '/' . $newdir . $basename);
             }
             // If we are on windows, fix the filename and URL
             if (DIRECTORY_SEPARATOR != '/') {
                 $new_filename_sys = str_replace('/', DIRECTORY_SEPARATOR, $new_filename_sys);
                 $new_url = str_replace(DIRECTORY_SEPARATOR, '/', $new_url);
             }
             // Make sure the target directory exists
             if (!JFile::exists($new_path)) {
                 if (!JFolder::create($new_path)) {
                     $errmsg = JText::sprintf('ATTACH_ERROR_UNABLE_TO_SETUP_UPLOAD_DIR_S', $new_path) . ' (ERR 74)';
                     JError::raiseError(500, $errmsg);
                 }
                 AttachmentsHelper::write_empty_index_html($new_path);
             }
             // Move the file!
             if (!JFile::move($current_filename_sys, $new_filename_sys)) {
                 $errmsg = JText::sprintf('ATTACH_ERROR_RENAMING_FILE_S_TO_S', $old_filename_sys, $new_filename_sys) . ' (ERR 75)';
                 JError::raiseError(500, $errmsg);
             }
             // Verify the new system filename exists!
             if (!JFile::exists($new_filename_sys)) {
                 $errmsg = JText::sprintf('ATTACH_ERROR_NEW_SYSTEM_FILENAME_S_NOT_FOUND', $new_filename_sys) . ' (ERR 76)';
                 JError::raiseError(500, $errmsg);
             }
             // Update the record
             $attachment->filename_sys = $new_filename_sys;
             $attachment->url = $new_url;
             if (!$attachment->store()) {
                 $errmsg = $attachment->getError() . ' (ERR 77)';
                 JError::raiseError(500, $errmsg);
             }
             $numUpdated++;
         }
     }
     // Add warning if there are problem files
     if ($numMissing > 0) {
         $msg = JText::sprintf('ATTACH_ERROR_N_FILES_MISSING', $numMissing) . "<br/>" . $msg . "&nbsp;<br/>";
     }
     return $msg . JText::sprintf('ATTACH_REGENERATED_SYSTEM_FILENAMES_FOR_N_ATTACHMENTS', $numUpdated);
 }
Beispiel #15
0
 /**
  * Display a form for updating/editing an attachment
  */
 public function update()
 {
     // Call with: index.php?option=com_attachments&task=update&id=1&tmpl=component
     //		  or: component/attachments/update/id/1/tmpl/component
     // Make sure we have a valid attachment ID
     $id = JRequest::getInt('id');
     if (is_numeric($id)) {
         $id = (int) $id;
     } else {
         $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_ATTACHMENT_ID_N', $id) . ' (ERR 24)';
         JError::raiseError(500, $errmsg);
     }
     // Get the attachment record
     require_once JPATH_COMPONENT_SITE . '/models/attachment.php';
     $model = new AttachmentsModelAttachment();
     $model->setId($id);
     $attachment = $model->getAttachment();
     if (!$attachment) {
         $errmsg = JText::sprintf('ATTACH_ERROR_CANNOT_UPDATE_ATTACHMENT_INVALID_ID_N', $id) . ' (ERR 25)';
         JError::raiseError(500, $errmsg);
     }
     // Get the component parameters
     jimport('joomla.application.component.helper');
     $params = JComponentHelper::getParams('com_attachments');
     // Get the article/parent handler
     $parent_id = $attachment->parent_id;
     $parent_type = $attachment->parent_type;
     $parent_entity = $attachment->parent_entity;
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     if (!$apm->attachmentsPluginInstalled($parent_type)) {
         $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $parent_type) . ' (ERR 26)';
         JError::raiseError(500, $errmsg);
     }
     $parent = $apm->getAttachmentsPlugin($parent_type);
     // Check to make sure we can edit it
     if (!$parent->userMayEditAttachment($attachment)) {
         return JError::raiseError(404, JText::_('JERROR_ALERTNOAUTHOR') . ' (ERR 27)');
     }
     // Set up the entity name for display
     $parent_entity_name = JText::_('ATTACH_' . $parent_entity);
     // Verify that this user may add attachments to this parent
     $user = JFactory::getUser();
     $new_parent = false;
     if ($parent_id === null) {
         $parent_id = 0;
         $new_parent = true;
     }
     // Make sure the attachments directory exists
     $upload_dir = JPATH_BASE . '/' . AttachmentsDefines::$ATTACHMENTS_SUBDIR;
     $secure = $params->get('secure', false);
     if (!AttachmentsHelper::setup_upload_directory($upload_dir, $secure)) {
         $errmsg = JText::sprintf('ATTACH_ERROR_UNABLE_TO_SETUP_UPLOAD_DIR_S', $upload_dir) . ' (ERR 28)';
         JError::raiseError(500, $errmsg);
     }
     // Make sure the update parameter is legal
     $update = JRequest::getWord('update');
     if ($update && !in_array($update, AttachmentsDefines::$LEGAL_URI_TYPES)) {
         $update = false;
     }
     // Suppress the display filename if we are switching from file to url
     $display_name = $attachment->display_name;
     if ($update && $update != $attachment->uri_type) {
         $attachment->display_name = '';
     }
     // Set up the view
     require_once JPATH_COMPONENT_SITE . '/views/update/view.html.php';
     $view = new AttachmentsViewUpdate();
     $from = JRequest::getWord('from', 'closeme');
     AttachmentsHelper::add_view_urls($view, 'update', $parent_id, $attachment->parent_type, $id, $from);
     $view->update = $update;
     $view->new_parent = $new_parent;
     $view->attachment = $attachment;
     $view->parent = $parent;
     $view->params = $params;
     $view->from = $from;
     $view->Itemid = JRequest::getInt('Itemid', 1);
     $view->error = false;
     $view->error_msg = false;
     $view->display();
 }
Beispiel #16
0
 /**
  * Import attachment data from a CSV file
  *
  * The CSV file must have the field names in the first row
  *
  * @param string $filename the filename of the CSV file
  * @param bool $verify_parent if true, each attachments parent must exist
  * @param bool $update if true, if the attachment exists, update it (or create a new one)
  * @param bool $dry_run do everything except actually add entries to attachment table in the database
  *
  * @return array of IDs of the imported attachemnts (if $dry_run, number that would have been imported), or error message
  */
 public static function importAttachmentsFromCSVFile($filename, $verify_parent = true, $update = false, $dry_run = false)
 {
     $db = JFactory::getDBO();
     // Open the CSV file
     $line_num = 0;
     $f = @fopen($filename, 'r');
     if (!$f) {
         return JText::sprintf('ATTACH_ERROR_UNABLE_TO_OPEN_CSV_FILE_S', $filename) . ' (ERR 85)';
     }
     // Parse the first row to process field names and indeces
     $field = AttachmentsImport::_parseFieldNames($f);
     $line_num += 1;
     if (!is_array($field)) {
         return $field;
     }
     // Get the default access level from the Attachments options
     jimport('joomla.application.component.helper');
     $params = JComponentHelper::getParams('com_attachments');
     $default_access_level = $params->get('default_access_level', AttachmentsDefines::$DEFAULT_ACCESS_LEVEL_ID);
     // Load the attachents parent manager
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     // Process the CSV data
     if ($dry_run) {
         $ids_ok = 0;
     } else {
         $ids_ok = array();
     }
     iconv_set_encoding("internal_encoding", "UTF-8");
     setlocale(LC_ALL, 'en_US.UTF-8');
     while (!feof($f)) {
         // Read the next line
         $adata = fgetcsv($f);
         $line_num += 1;
         $line_str = '  [LINE: ' . $line_num . '] ';
         // Skip blank lines
         if (!$adata) {
             continue;
         }
         // get the attachment ID
         $attachment_id = $adata[$field['id']];
         if (!is_numeric($attachment_id)) {
             return JText::sprintf('ATTACH_ERROR_BAD_ATTACHMENT_ID_S', $attachment_id) . $line_str . ' (ERR 86)';
         }
         $attachment_id = (int) $attachment_id;
         $parent_type = $adata[$field['parent_type']];
         $parent_entity = strtolower($adata[$field['parent_entity']]);
         $parent_id = (int) $adata[$field['parent_id']];
         // Make sure it is not a 'section' attachment
         if ($parent_entity == 'section') {
             return JText::sprintf('ATTACH_ERROR_SECTION_ATTACHMENT_NOT_ALLOWED_ID', $attachment_id) . $line_str . ' (ERR 86B)';
         }
         // Get the attachment parent object
         if (!$apm->attachmentsPluginInstalled($parent_type)) {
             return JText::sprintf('ATTACH_ERROR_UNKNOWN_PARENT_TYPE_S', $parent_type) . $line_str . ' (ERR 87)';
         }
         $parent = $apm->getAttachmentsPlugin($parent_type);
         // Does the parent exist?
         if ($verify_parent) {
             // Make sure a parent with the specified ID exists
             if (!$parent->parentExists($parent_id, $parent_entity)) {
                 return JText::sprintf('ATTACH_ERROR_UNKNOWN_PARENT_ID_N', $parent_id) . $line_str . ' (ERR 88)';
             }
             // Double-check by comparing the title
             $attachment_parent_title = $adata[$field['parent_title']];
             $parent_title = $parent->getTitle($parent_id, $parent_entity);
             if (!AttachmentsImport::utf8StringsEqual($parent_title, $attachment_parent_title)) {
                 return JText::sprintf('ATTACH_ERROR_PARENT_TITLE_MISMATCH_ID_N_TITLE_S_S', $parent_id, $parent_title, $attachment_parent_title) . $line_str . ' (ERR 89)';
             }
         }
         // Check the creator username
         $creator_id = (int) $adata[$field['created_by']];
         $attachment_creator_username = $adata[$field['created_by_username']];
         $query = $db->getQuery(true);
         $query->select('username')->from('#__users')->where('id = ' . (int) $creator_id);
         $db->setQuery($query, 0, 1);
         $creator_username = $db->loadResult();
         if (empty($creator_username) || $db->getErrorNum()) {
             return JText::sprintf('ATTACH_ERROR_UNABLE_TO_FIND_CREATOR_ID_S', $creator_id, $attachment_creator_username) . $line_str . ' (ERR 90)';
         }
         if (!AttachmentsImport::utf8StringsEqual($creator_username, $attachment_creator_username)) {
             return JText::sprintf('ATTACH_ERROR_CREATOR_USERNAME_MISMATCH_ID_S_S', $creator_id, $attachment_creator_username, $creator_username) . $line_str . ' (ERR 91)';
         }
         // Check the modifier name
         $modifier_id = (int) $adata[$field['modified_by']];
         $attachment_modifier_username = $adata[$field['modified_by_username']];
         $query = $db->getQuery(true);
         $query->select('username')->from('#__users')->where('id = ' . (int) $modifier_id);
         $db->setQuery($query, 0, 1);
         $modifier_username = $db->loadResult();
         if (empty($modifier_username) || $db->getErrorNum()) {
             return JText::sprintf('ATTACH_ERROR_UNABLE_TO_FIND_MODIFIER_ID_S', $modifier_id, $attachment_modifier_username) . $line_str . ' (ERR 92)';
         }
         if (!AttachmentsImport::utf8StringsEqual($modifier_username, $attachment_modifier_username)) {
             return JText::sprintf('ATTACH_ERROR_MODIFIER_USERNAME_MISMATCH_ID_S_S', $modifier_id, $attachment_modifier_username, $modifier_username) . $line_str . ' (ERR 93)';
         }
         // Construct an attachments entry
         JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_attachments/tables');
         $attachment = JTable::getInstance('Attachment', 'AttachmentsTable');
         if ($update) {
             // The attachment ID cannot be 0 for updating!
             if ($attachment_id == 0) {
                 return JText::_('ATTACH_ERROR_CANNOT_MODIFY_ATTACHMENT_ZERO_ID') . $line_str . ' (ERR 94)';
             }
             // Load the data from the attachment to be updated (or create new one)
             if (!$attachment->load($attachment_id)) {
                 $attachment->reset();
             }
         } else {
             // Create new attachment
             $attachment->reset();
         }
         // Copy in the data from the CSV file
         foreach (AttachmentsImport::$field_names as $fname) {
             if ($fname != 'id' && !in_array($fname, AttachmentsImport::$extra_field_names)) {
                 $attachment->{$fname} = $adata[$field[$fname]];
             }
         }
         // Do any necessary overrides
         $attachment->parent_entity = $parent_entity;
         // ??? what about parent_entity_name?
         $attachment->access = $default_access_level;
         $attachment->file_size = (int) $adata[$field['file_size']];
         if ($dry_run) {
             $ids_ok++;
         } else {
             // Store the new/updated attachment
             if ($attachment->store()) {
                 $ids_ok[] = $attachment->getDbo()->insertid();
             } else {
                 return JText::sprintf('ATTACH_ERROR_STORING_ATTACHMENT_S', $attachment->getError()) . ' (ERR 95)';
             }
         }
     }
     fclose($f);
     return $ids_ok;
 }
Beispiel #17
0
 /**
  * Delete attachment(s)
  */
 public function delete()
 {
     // Check for request forgeries
     JSession::checkToken() or die(JText::_('JINVALID_TOKEN'));
     // Get ready
     $app = JFactory::getApplication();
     jimport('joomla.filesystem.file');
     require_once JPATH_SITE . '/components/com_attachments/helper.php';
     // Get the attachments parent manager
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     // Get attachments to remove from the request
     $cid = JRequest::getVar('cid', array(), '', 'array');
     $deleted_ids = array();
     if (count($cid)) {
         $model = $this->getModel('Attachment');
         $attachment = $model->getTable();
         // Loop through the attachments and delete them one-by-one
         foreach ($cid as $attachment_id) {
             // Load the attachment object
             $id = (int) $attachment_id;
             if ($id == 0 or !$attachment->load($id)) {
                 $errmsg = JText::sprintf('ATTACH_ERROR_CANNOT_DELETE_INVALID_ATTACHMENT_ID_N', $id) . ' (ERR 166)';
                 JError::raiseError(500, $errmsg);
             }
             $parent_id = $attachment->parent_id;
             $parent_type = $attachment->parent_type;
             $parent_entity = $attachment->parent_entity;
             // Get the article/parent handler
             JPluginHelper::importPlugin('attachments');
             $apm = getAttachmentsPluginManager();
             if (!$apm->attachmentsPluginInstalled($parent_type)) {
                 $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $parent_type) . ' (ERR 167)';
                 JError::raiseError(500, $errmsg);
             }
             $parent = $apm->getAttachmentsPlugin($parent_type);
             // If we may not delete it, complain!
             if ($parent->userMayDeleteAttachment($attachment)) {
                 // Delete the actual file
                 if (JFile::exists($attachment->filename_sys)) {
                     JFile::delete($attachment->filename_sys);
                     AttachmentsHelper::clean_directory($attachment->filename_sys);
                 }
                 $deleted_ids[] = $id;
             } else {
                 $parent_entity = $parent->getCanonicalEntityId($parent_entity);
                 $errmsg = JText::sprintf('ATTACH_ERROR_NO_PERMISSION_TO_DELETE_S_ATTACHMENT_S_ID_N', $parent_entity, $attachment->filename, $id);
                 $app->enqueueMessage($errmsg, 'warning');
             }
         }
         // Delete entries in the attachments table for deleted attachments
         if (!empty($deleted_ids)) {
             $db = JFactory::getDBO();
             $query = $db->getQuery(true);
             $query->delete('#__attachments')->where("id IN (" . implode(',', $deleted_ids) . ")");
             $db->setQuery($query);
             if (!$db->query()) {
                 $errmsg = $db->getErrorMsg() . ' (ERR 168)';
                 JError::raiseError(500, $errmsg);
             }
         }
     }
     // Figure out how to redirect
     $from = JRequest::getWord('from');
     $known_froms = array('frontpage', 'article', 'editor', 'closeme');
     if (in_array($from, $known_froms)) {
         // Get the parent info from the last attachment
         $parent_id = $attachment->parent_id;
         $parent_type = $attachment->parent_type;
         $parent_entity = $attachment->parent_entity;
         // Get the article/parent handler
         if (!$apm->attachmentsPluginInstalled($parent_type)) {
             $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $parent_type) . ' (ERR 169)';
             JError::raiseError(500, $errmsg);
         }
         $parent = $apm->getAttachmentsPlugin($parent_type);
         $parent_entity = $parent->getCanonicalEntityId($parent_entity);
         // Make sure the parent exists
         // NOTE: $parent_id===null means the parent is being created
         if ($parent_id !== null && !$parent->parentExists($parent_id, $parent_entity)) {
             $parent_entity_name = JText::_('ATTACH_' . $parent_entity);
             $errmsg = JText::sprintf('ATTACH_ERROR_CANNOT_DELETE_INVALID_S_ID_N', $parent_entity_name, $parent_id) . ' (ERR 170)';
             JError::raiseError(500, $errmsg);
         }
         // If there is no parent_id, the parent is being created, use the username instead
         if (!$parent_id) {
             $pid = 0;
         } else {
             $pid = (int) $parent_id;
         }
         // Close the iframe and refresh the attachments list in the parent window
         require_once JPATH_SITE . '/components/com_attachments/javascript.php';
         $uri = JFactory::getURI();
         $base_url = $uri->base(true);
         $lang = JRequest::getCmd('lang', '');
         AttachmentsJavascript::closeIframeRefreshAttachments($base_url, $parent_type, $parent_entity, $pid, $lang, $from);
         exit;
     }
     $this->setRedirect('index.php?option=' . $this->option);
 }
Beispiel #18
0
 /**
  * Method to get an array of data items.
  *
  * @return	mixed	An array of data items on success, false on failure.
  * @since	1.6
  */
 public function getItems()
 {
     $items = parent::getItems();
     if ($items === false) {
         return false;
     }
     $good_items = array();
     // Update the attachments with information about thier parents
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     foreach ($items as $item) {
         $parent_id = $item->parent_id;
         $parent_type = $item->parent_type;
         $parent_entity = $item->parent_entity;
         if (!$apm->attachmentsPluginInstalled($parent_type)) {
             $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $parent_type . ':' . $parent_entity . ' (ID ' . (string) $item->id . ')') . ' (ERR 115)';
             $app = JFactory::getApplication();
             $app->enqueueMessage($errmsg, 'warning');
             continue;
         }
         $parent = $apm->getAttachmentsPlugin($parent_type);
         if ($parent) {
             // Handle the normal case
             $item->parent_entity_type = JText::_('ATTACH_' . $parent_entity);
             $title = $parent->getTitle($parent_id, $parent_entity);
             $item->parent_exists = $parent->parentExists($parent_id, $parent_entity);
             if ($item->parent_exists && $title) {
                 $item->parent_title = $title;
                 $item->parent_url = JFilterOutput::ampReplace($parent->getEntityViewURL($parent_id, $parent_entity));
             } else {
                 $item->parent_title = JText::sprintf('ATTACH_NO_PARENT_S', $item->parent_entity_type);
                 $item->parent_url = '';
             }
         } else {
             // Handle pathalogical case where there is no parent handler
             // (eg, deleted component)
             $item->parent_exists = false;
             $item->parent_entity_type = $parent_entity;
             $item->parent_title = JText::_('ATTACH_UNKNOWN');
             $item->parent_published = false;
             $item->parent_archived = false;
             $item->parent_url = '';
         }
         $good_items[] = $item;
     }
     // Return from the cache
     return $good_items;
 }
 /**
  * Method is called by
  *
  * @access	public
  */
 public function onAfterImport($context, &$xml, $options)
 {
     JLog::add(new JLogEntry(__METHOD__, JLOG::DEBUG, 'plg_j2xml_attachments'));
     JLog::add(new JLogEntry($context, JLOG::DEBUG, 'plg_j2xml_attachments'));
     if (PHP_SAPI == 'cli') {
         JLog::addLogger(array('logger' => 'echo', 'extension' => 'plg_j2xml_attachments'), JLOG::ALL & ~JLOG::DEBUG, array('plg_j2xml_attachments'));
     } else {
         JLog::addLogger(array('logger' => $options->get('logger', 'messagequeue'), 'extension' => 'plg_j2xml_attachments'), JLOG::ALL & ~JLOG::DEBUG, array('plg_j2xml_attachments'));
     }
     if (version_compare(J2XMLVersion::getShortVersion(), '15.9.5') == -1) {
         JLog::add(new JLogEntry(JText::_('PLG_J2XML_ATTACHMENTS') . ' ' . JText::_('PLG_J2XML_ATTACHMENTS_MSG_REQUIREMENTS_LIB'), JLOG::WARNING, 'plg_j2xml_attachments'));
         return false;
     }
     // Check if component is not installed
     if (!file_exists(JPATH_ADMINISTRATOR . '/components/com_attachments/attachments.php')) {
         JLog::add(new JLogEntry(JText::_('PLG_J2XML_ATTACHMENTS') . ' ' . JText::_('PLG_J2XML_ATTACHMENTS_MSG_REQUIREMENTS_COM'), JLOG::WARNING, 'plg_j2xml_attachments'));
         return false;
     }
     // Check if component is not enabled
     if (!JComponentHelper::isEnabled('com_attachments', true)) {
         JLog::add(new JLogEntry(JText::_('PLG_J2XML_ATTACHMENTS') . ' ' . JText::_('PLG_J2XML_ATTACHMENTS_MSG_REQUIREMENTS_COM'), JLOG::WARNING, 'plg_j2xml_attachments'));
         return false;
     }
     jimport('eshiol.j2xml.importer');
     $app = JFactory::getApplication();
     $db = JFactory::getDBO();
     foreach ($xml->xpath("/j2xml/attachment[parent_type = 'com_content' and parent_entity = 'article']") as $record) {
         $importer = new J2XMLImporter();
         $importer->prepareData($record, $data, $options);
         $attachment = new stdClass();
         $attachment->filename = html_entity_decode($data['filename']);
         $attachment->file_type = $data['file_type'];
         $attachment->file_size = $data['file_size'];
         $attachment->parent_type = $data['parent_type'];
         $attachment->parent_entity = $data['parent_entity'];
         $attachment->parent_id = $importer->getArticledId($data['parent_id']);
         $attachment->uri_type = $data['uri_type'];
         if ($data['uri_type'] == 'url') {
             $attachment->url = $data['url'];
             $attachment->filename_sys = '';
         } elseif (isset($data['file'])) {
             require_once JPATH_SITE . '/components/com_attachments/helper.php';
             // Get the component parameters
             jimport('joomla.application.component.helper');
             $params = JComponentHelper::getParams('com_attachments');
             // Define where the attachments go
             $upload_url = AttachmentsDefines::$ATTACHMENTS_SUBDIR;
             $upload_dir = JPATH_SITE . '/' . $upload_url;
             // Get the parent plugin manager
             JPluginHelper::importPlugin('attachments');
             $apm = getAttachmentsPluginManager();
             // Get the parent object
             $parent = $apm->getAttachmentsPlugin($attachment->parent_type);
             // Construct the system filename and url (based on entities, etc)
             $newdir = $parent->getAttachmentPath($attachment->parent_entity, $attachment->parent_id, null);
             $fullpath = $upload_dir . '/' . $newdir;
             // Make sure the directory exists
             if (!JFile::exists($fullpath)) {
                 jimport('joomla.filesystem.folder');
                 if (!JFolder::create($fullpath)) {
                     $errmsg = JText::sprintf('ATTACH_ERROR_UNABLE_TO_SETUP_UPLOAD_DIR_S', $upload_dir) . ' (ERR 34)';
                     JError::raiseError(500, $errmsg);
                 }
                 require_once JPATH_SITE . '/components/com_attachments/helper.php';
                 AttachmentsHelper::write_empty_index_html($fullpath);
             }
             $attachment->filename_sys = $fullpath . $attachment->filename;
             file_put_contents($attachment->filename_sys, base64_decode($data['file']));
             $attachment->filename_sys = utf8_encode($attachment->filename_sys);
             $attachment->filename = utf8_encode($attachment->filename);
             $attachment->url = $upload_url . '/' . $newdir . $attachment->filename;
         } else {
             JLog::add(new JLogEntry(JText::sprintf('PLG_J2XML_ATTACHMENTS_MSG_ATTACHMENT_NOT_EXPORTED', $attachment->filename), JLOG::WARNING, 'plg_j2xml_attachments'));
             return;
         }
         $attachment->url_valid = $data['url_valid'];
         $attachment->url_relative = $data['url_relative'];
         $attachment->url_verify = $data['url_verify'];
         $attachment->display_name = $data['display_name'];
         $attachment->description = $data['description'];
         $attachment->icon_filename = $data['icon_filename'];
         $attachment->access = $importer->getAccessId($data['access']);
         $attachment->state = $data['state'];
         $attachment->user_field_1 = $data['user_field_1'];
         $attachment->user_field_2 = $data['user_field_2'];
         $attachment->user_field_3 = $data['user_field_3'];
         $attachment->created = $data['created'];
         $attachment->created_by = $importer->getUserId($data['created_by'], $this->_user_id);
         $attachment->modified = $data['modified'];
         $attachment->modified_by = $importer->getUserId($data['modified_by'], 0);
         $attachment->download_count = $data['download_count'];
         $query = $db->getQuery(true);
         $query->select($db->quoteName('id'));
         $query->from($db->quoteName('#__attachments'));
         $query->where($db->quoteName('parent_type') . '=' . $db->quote($attachment->parent_type));
         $query->where($db->quoteName('parent_entity') . '=' . $db->quote($attachment->parent_entity));
         $query->where($db->quoteName('filename') . '=' . $db->quote($attachment->filename));
         $query->where($db->quoteName('uri_type') . '=' . $db->quote($attachment->uri_type));
         $db->setQuery($query);
         $id = $db->loadResult();
         if ($id) {
             $attachments->id = $id;
             if ($db->updateObject('#__attachments', $attachments, 'id')) {
                 JLog::add(new JLogEntry(JText::sprintf('PLG_J2XML_ATTACHMENTS_MSG_ATTACHMENT_IMPORTED', $attachment->filename), JLOG::INFO, 'plg_j2xml_attachments'));
             } else {
                 JLog::add(new JLogEntry(JText::sprintf('PLG_J2XML_ATTACHMENTS_MSG_ATTACHMENT_NOT_IMPORTED', $attachment->filename), JLOG::INFO, 'plg_j2xml_attachments'));
             }
         } else {
             if ($db->insertObject('#__attachments', $attachment)) {
                 JLog::add(new JLogEntry(JText::sprintf('PLG_J2XML_ATTACHMENTS_MSG_ATTACHMENT_IMPORTED', $attachment->filename), JLOG::INFO, 'plg_j2xml_attachments'));
             } else {
                 JLog::add(new JLogEntry(JText::sprintf('PLG_J2XML_ATTACHMENTS_MSG_ATTACHMENT_NOT_IMPORTED', $attachment->filename), JLOG::INFO, 'plg_j2xml_attachments'));
             }
         }
     }
     return true;
 }
Beispiel #20
0
 /**
  * Get the parent class object
  *
  * @return the parent class object
  */
 public function &getParentClass()
 {
     if ($this->_parent_type == null) {
         $errmsg = JText::_('ATTACH_ERROR_NO_PARENT_TYPE_SPECIFIED') . ' (ERR 54)';
         JError::raiseError(500, $errmsg);
     }
     if ($this->_parent_class == null) {
         // Get the parent handler
         JPluginHelper::importPlugin('attachments');
         $apm = getAttachmentsPluginManager();
         if (!$apm->attachmentsPluginInstalled($this->_parent_type)) {
             $errmsg = JText::sprintf('ATTACH_ERROR_INVALID_PARENT_TYPE_S', $parent_type) . ' (ERR 55)';
             JError::raiseError(500, $errmsg);
         }
         $this->_parent_class = $apm->getAttachmentsPlugin($this->_parent_type);
     }
     return $this->_parent_class;
 }
        // Note categories cannot be created or edited from the frontend
        if ($parent_entity == 'category') {
            return false;
        }
        // Deal with articles (in frontend)
        $id = null;
        if ($view == 'article' or $view == 'form') {
            $id = JRequest::getInt('a_id', $default = null);
        } else {
            $id = false;
        }
        // If we got one, convert it to an int
        if (is_numeric($id)) {
            $id = (int) $id;
        }
        return $id;
    }
    /** Known from keywords
     *
     * Attachment pop-dialogs will be closed using javascript if they are called from pages of these 'from' types
     *
     * @retrun array  An array of known tokens (strings)
     */
    public function knownFroms()
    {
        return array_merge(parent::knownFroms(), array('frontpage', 'featured', 'article', 'category', 'details'));
    }
}
/** Register this attachments type */
$apm = getAttachmentsPluginManager();
$apm->addParentType('com_content');
Beispiel #22
0
 /**
  * Display the list view
  */
 public function display($tpl = null)
 {
     // Fail gracefully if the Attachments plugin framework plugin is disabled
     if (!JPluginHelper::isEnabled('attachments', 'attachments_plugin_framework')) {
         echo '<h1>' . JText::_('ATTACH_WARNING_ATTACHMENTS_PLUGIN_FRAMEWORK_DISABLED') . '</h1>';
         return;
     }
     $this->items = $this->get('Items');
     $this->state = $this->get('State');
     $this->pagination = $this->get('Pagination');
     // Check for errors.
     if (count($errors = $this->get('Errors'))) {
         JError::raiseError(500, implode("\n", $errors) . ' (ERR 175)');
         return false;
     }
     // Get the params
     jimport('joomla.application.component.helper');
     $params = JComponentHelper::getParams('com_attachments');
     $this->params = $params;
     // Get the access level names for the display
     $db = JFactory::getDBO();
     $query = $db->getQuery(true);
     $query->select('*')->from('#__viewlevels');
     $db->setQuery($query);
     $levels = $db->loadObjectList();
     if ($db->getErrorNum()) {
         $errmsg = $db->stderr() . ' (ERR 176)';
         JError::raiseError(500, $errmsg);
     }
     $level_name = array();
     foreach ($levels as $level) {
         // NOTE: We do not translate the access level title
         $level_name[$level->id] = $level->title;
     }
     $this->level_name = $level_name;
     // Construct the special HTML lists
     $lists = array();
     // Determine types of parents for which attachments should be displayed
     $list_for_parents_default = 'ALL';
     $suppress_obsolete_attachments = $params->get('suppress_obsolete_attachments', false);
     if ($suppress_obsolete_attachments) {
         $list_for_parents_default = 'PUBLISHED';
     }
     $app = JFactory::getApplication();
     $list_for_parents = $app->getUserStateFromRequest('com_attachments.listAttachments.list_for_parents', 'list_for_parents', $list_for_parents_default, 'word');
     $lists['list_for_parents'] = JString::strtolower($list_for_parents);
     // Add the drop-down menu to decide which attachments to show
     $filter_parent_state = $this->state->get('filter.parent_state', 'ALL');
     $filter_parent_state_options = array();
     $filter_parent_state_options[] = JHtml::_('select.option', 'ALL', JText::_('ATTACH_ALL_PARENTS'));
     $filter_parent_state_options[] = JHtml::_('select.option', 'PUBLISHED', JText::_('ATTACH_PUBLISHED_PARENTS'));
     $filter_parent_state_options[] = JHtml::_('select.option', 'UNPUBLISHED', JText::_('ATTACH_UNPUBLISHED_PARENTS'));
     $filter_parent_state_options[] = JHtml::_('select.option', 'ARCHIVED', JText::_('ATTACH_ARCHIVED_PARENTS'));
     $filter_parent_state_options[] = JHtml::_('select.option', 'TRASHED', JText::_('ATTACH_TRASHED_PARENTS'));
     $filter_parent_state_options[] = JHtml::_('select.option', 'NONE', JText::_('ATTACH_NO_PARENTS'));
     $filter_parent_state_tooltip = JText::_('ATTACH_SHOW_FOR_PARENTS_TOOLTIP');
     $lists['filter_parent_state_menu'] = JHtml::_('select.genericlist', $filter_parent_state_options, 'filter_parent_state', 'class="inputbox" onChange="document.adminForm.submit();" title="' . $filter_parent_state_tooltip . '"', 'value', 'text', $filter_parent_state);
     $this->filter_parent_state = $filter_parent_state;
     // Add the drop-down menu to filter for types of entities
     $filter_entity = $this->state->get('filter.entity', 'ALL');
     $filter_entity_options = array();
     $filter_entity_options[] = JHtml::_('select.option', 'ALL', JText::_('ATTACH_ALL_TYPES'));
     JPluginHelper::importPlugin('attachments');
     $apm = getAttachmentsPluginManager();
     $entity_info = $apm->getInstalledEntityInfo();
     foreach ($entity_info as $einfo) {
         $filter_entity_options[] = JHtml::_('select.option', $einfo['id'], $einfo['name_plural']);
     }
     $filter_entity_tooltip = JText::_('ATTACH_FILTER_ENTITY_TOOLTIP');
     $lists['filter_entity_menu'] = JHtml::_('select.genericlist', $filter_entity_options, 'filter_entity', 'class="inputbox" onChange="this.form.submit();" ' . 'title="' . $filter_entity_tooltip . '"', 'value', 'text', $filter_entity);
     $this->lists = $lists;
     // Figure out how many columns
     $num_columns = 10;
     if ($params->get('user_field_1_name')) {
         $num_columns++;
     }
     if ($params->get('user_field_2_name')) {
         $num_columns++;
     }
     if ($params->get('user_field_3_name')) {
         $num_columns++;
     }
     if ($params->get('secure', false)) {
         $num_columns++;
     }
     $this->num_columns = $num_columns;
     // get the version number
     require_once JPATH_SITE . '/components/com_attachments/defines.php';
     $this->version = AttachmentsDefines::$ATTACHMENTS_VERSION;
     $this->project_url = AttachmentsDefines::$PROJECT_URL;
     // Add the style sheets
     JHtml::stylesheet('com_attachments/attachments_admin.css', array(), true);
     $lang = JFactory::getLanguage();
     if ($lang->isRTL()) {
         JHtml::stylesheet('com_attachments/attachments_admin_rtl.css', array(), true);
     }
     // Set the toolbar
     $this->addToolBar();
     // Display the attachments
     parent::display($tpl);
 }