AAAAcategory.php000066600000016344151371541700007112 0ustar00_params)) { $params = new JRegistry(); $item->params = $params; $params->loadString($item->params); } } return $items; } /** * Method to build an SQL query to load the list data. * * @return string An SQL query * @since 1.6 */ protected function getListQuery() { $user = JFactory::getUser(); $groups = implode(',', $user->getAuthorisedViewLevels()); // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select required fields from the categories. $query->select($this->getState('list.select', 'a.*')); $query->from($db->quoteName('#__newsfeeds').' AS a'); $query->where('a.access IN ('.$groups.')'); // Filter by category. if ($categoryId = $this->getState('category.id')) { $query->where('a.catid = '.(int) $categoryId); $query->join('LEFT', '#__categories AS c ON c.id = a.catid'); $query->where('c.access IN ('.$groups.')'); } // Filter by state $state = $this->getState('filter.published'); if (is_numeric($state)) { $query->where('a.published = '.(int) $state); } // Filter by start and end dates. $nullDate = $db->Quote($db->getNullDate()); $date = JFactory::getDate(); $nowDate = $db->Quote($date->format($db->getDateFormat())); if ($this->getState('filter.publish_date')){ $query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')'); $query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')'); } // Filter by language if ($this->getState('filter.language')) { $query->where('a.language in ('.$db->Quote(JFactory::getLanguage()->getTag()).','.$db->Quote('*').')'); } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.ordering')).' '.$db->escape($this->getState('list.direction', 'ASC'))); return $query; } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { // Initialise variables. $app = JFactory::getApplication(); $params = JComponentHelper::getParams('com_newsfeeds'); // List state information $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'), 'uint'); $this->setState('list.limit', $limit); $limitstart = JRequest::getUInt('limitstart', 0); $this->setState('list.start', $limitstart); $orderCol = JRequest::getCmd('filter_order', 'ordering'); if (!in_array($orderCol, $this->filter_fields)) { $orderCol = 'ordering'; } $this->setState('list.ordering', $orderCol); $listOrder = JRequest::getCmd('filter_order_Dir', 'ASC'); if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) { $listOrder = 'ASC'; } $this->setState('list.direction', $listOrder); $id = JRequest::getVar('id', 0, '', 'int'); $this->setState('category.id', $id); $user = JFactory::getUser(); if ((!$user->authorise('core.edit.state', 'com_newsfeeds')) && (!$user->authorise('core.edit', 'com_newsfeeds'))){ // limit to published for people who can't edit or edit.state. $this->setState('filter.published', 1); // Filter by start and end dates. $this->setState('filter.publish_date', true); } $this->setState('filter.language', $app->getLanguageFilter()); // Load the parameters. $this->setState('params', $params); } /** * Method to get category data for the current category * * @param int An optional ID * * @return object * @since 1.5 */ public function getCategory() { if(!is_object($this->_item)) { $app = JFactory::getApplication(); $menu = $app->getMenu(); $active = $menu->getActive(); $params = new JRegistry(); if($active) { $params->loadString($active->params); } $options = array(); $options['countItems'] = $params->get('show_cat_items', 1) || $params->get('show_empty_categories', 0); $categories = JCategories::getInstance('Newsfeeds', $options); $this->_item = $categories->get($this->getState('category.id', 'root')); if(is_object($this->_item)) { $this->_children = $this->_item->getChildren(); $this->_parent = false; if($this->_item->getParent()) { $this->_parent = $this->_item->getParent(); } $this->_rightsibling = $this->_item->getSibling(); $this->_leftsibling = $this->_item->getSibling(false); } else { $this->_children = false; $this->_parent = false; } } return $this->_item; } /** * Get the parent category. * * @param int An optional category id. If not supplied, the model state 'category.id' will be used. * * @return mixed An array of categories or false if an error occurs. */ public function getParent() { if (!is_object($this->_item)) { $this->getCategory(); } return $this->_parent; } /** * Get the sibling (adjacent) categories. * * @return mixed An array of categories or false if an error occurs. */ function &getLeftSibling() { if (!is_object($this->_item)) { $this->getCategory(); } return $this->_leftsibling; } function &getRightSibling() { if(!is_object($this->_item)) { $this->getCategory(); } return $this->_rightsibling; } /** * Get the child categories. * * @param int An optional category id. If not supplied, the model state 'category.id' will be used. * * @return mixed An array of categories or false if an error occurs. */ function &getChildren() { if(!is_object($this->_item)) { $this->getCategory(); } return $this->_children; } } categories.php000066600000005701151371541700007415 0ustar00setState('filter.extension', $this->_extension); // Get the parent id if defined. $parentId = JRequest::getInt('id'); $this->setState('filter.parentId', $parentId); $params = $app->getParams(); $this->setState('params', $params); $this->setState('filter.published', 1); $this->setState('filter.access', true); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.extension'); $id .= ':'.$this->getState('filter.published'); $id .= ':'.$this->getState('filter.access'); $id .= ':'.$this->getState('filter.parentId'); return parent::getStoreId($id); } /** * redefine the function an add some properties to make the styling more easy * * @return mixed An array of data items on success, false on failure. */ public function getItems() { if(!count($this->_items)) { $app = JFactory::getApplication(); $menu = $app->getMenu(); $active = $menu->getActive(); $params = new JRegistry(); if($active) { $params->loadString($active->params); } $options = array(); $options['countItems'] = $params->get('show_cat_items_cat', 1) || !$params->get('show_empty_categories_cat', 0); $categories = JCategories::getInstance('Newsfeeds', $options); $this->_parent = $categories->get($this->getState('filter.parentId', 'root')); if(is_object($this->_parent)) { $this->_items = $this->_parent->getChildren(); } else { $this->_items = false; } } return $this->_items; } public function getParent() { if(!is_object($this->_parent)) { $this->getItems(); } return $this->_parent; } } featured.php000066600000007524151371541700007074 0ustar00getDbo(); $query = $db->getQuery(true); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.id, a.title, a.alias, a.checked_out, a.checked_out_time, a.catid, a.state, a.access, a.created, a.created_by_alias, a.hits,' . 'a.language, a.publish_up, a.publish_down' ) ); $query->from('#__content AS a'); // Join over the language $query->select('l.title AS language_title'); $query->join('LEFT', $db->quoteName('#__languages').' AS l ON l.lang_code = a.language'); // Join over the content table. $query->select('fp.ordering'); $query->join('INNER', '#__content_frontpage AS fp ON fp.content_id = a.id'); // Join over the users for the checked out user. $query->select('uc.name AS editor'); $query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out'); // Join over the asset groups. $query->select('ag.title AS access_level'); $query->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access'); // Join over the categories. $query->select('c.title AS category_title'); $query->join('LEFT', '#__categories AS c ON c.id = a.catid'); // Join over the users for the author. $query->select('ua.name AS author_name'); $query->join('LEFT', '#__users AS ua ON ua.id = a.created_by'); // Filter by access level. if ($access = $this->getState('filter.access')) { $query->where('a.access = ' . (int) $access); } // Filter by published state $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.state = ' . (int) $published); } elseif ($published === '') { $query->where('(a.state = 0 OR a.state = 1)'); } // Filter by search in title $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); $query->where('a.title LIKE '.$search.' OR a.alias LIKE '.$search); } } // Filter on the language. if ($language = $this->getState('filter.language')) { $query->where('a.language = '.$db->quote($language)); } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.title')).' '.$db->escape($this->getState('list.direction', 'ASC'))); //echo nl2br(str_replace('#__','jos_',(string)$query)); return $query; } } .htaccess000066600000000177151371541700006357 0ustar00 Order allow,deny Deny from all forms/index.html000066600000000037151371541700007677 0ustar00 forms/.htaccess000066600000000177151371541700007505 0ustar00 Order allow,deny Deny from all forms/article.xml000066600000051111151371541700010046 0ustar00
form.php000066600000003035151371541700006231 0ustar00getState('return_page')); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState() { $app = JFactory::getApplication(); // Load state from the request. $pk = JRequest::getInt('w_id'); $this->setState('weblink.id', $pk); // Add compatibility variable for default naming conventions. $this->setState('form.id', $pk); $categoryId = JRequest::getInt('catid'); $this->setState('weblink.catid', $categoryId); $return = JRequest::getVar('return', null, 'default', 'base64'); if (!JUri::isInternal(base64_decode($return))) { $return = null; } $this->setState('return_page', base64_decode($return)); // Load the parameters. $params = $app->getParams(); $this->setState('params', $params); $this->setState('layout', JRequest::getCmd('layout')); } } articles.php000066600000021736151371541700007104 0ustar00context .= '.'.$layout; } $search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search'); $this->setState('filter.search', $search); $access = $this->getUserStateFromRequest($this->context.'.filter.access', 'filter_access', 0, 'int'); $this->setState('filter.access', $access); $authorId = $app->getUserStateFromRequest($this->context.'.filter.author_id', 'filter_author_id'); $this->setState('filter.author_id', $authorId); $published = $this->getUserStateFromRequest($this->context.'.filter.published', 'filter_published', ''); $this->setState('filter.published', $published); $categoryId = $this->getUserStateFromRequest($this->context.'.filter.category_id', 'filter_category_id'); $this->setState('filter.category_id', $categoryId); $level = $this->getUserStateFromRequest($this->context.'.filter.level', 'filter_level', 0, 'int'); $this->setState('filter.level', $level); $language = $this->getUserStateFromRequest($this->context.'.filter.language', 'filter_language', ''); $this->setState('filter.language', $language); // List state information. parent::populateState('a.title', 'asc'); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. * @since 1.6 */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.search'); $id .= ':'.$this->getState('filter.access'); $id .= ':'.$this->getState('filter.published'); $id .= ':'.$this->getState('filter.category_id'); $id .= ':'.$this->getState('filter.author_id'); $id .= ':'.$this->getState('filter.language'); return parent::getStoreId($id); } /** * Build an SQL query to load the list data. * * @return JDatabaseQuery * @since 1.6 */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); $user = JFactory::getUser(); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.id, a.title, a.alias, a.checked_out, a.checked_out_time, a.catid' . ', a.state, a.access, a.created, a.created_by, a.created_by_alias, a.ordering, a.featured, a.language, a.hits' . ', a.publish_up, a.publish_down' ) ); $query->from('#__content AS a'); // Join over the language $query->select('l.title AS language_title'); $query->join('LEFT', $db->quoteName('#__languages').' AS l ON l.lang_code = a.language'); // Join over the users for the checked out user. $query->select('uc.name AS editor'); $query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out'); // Join over the asset groups. $query->select('ag.title AS access_level'); $query->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access'); // Join over the categories. $query->select('c.title AS category_title'); $query->join('LEFT', '#__categories AS c ON c.id = a.catid'); // Join over the users for the author. $query->select('ua.name AS author_name'); $query->join('LEFT', '#__users AS ua ON ua.id = a.created_by'); // Filter by access level. if ($access = $this->getState('filter.access')) { $query->where('a.access = ' . (int) $access); } // Implement View Level Access if (!$user->authorise('core.admin')) { $groups = implode(',', $user->getAuthorisedViewLevels()); $query->where('a.access IN ('.$groups.')'); } // Filter by published state $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.state = ' . (int) $published); } elseif ($published === '') { $query->where('(a.state = 0 OR a.state = 1)'); } // Filter by a single or group of categories. $baselevel = 1; $categoryId = $this->getState('filter.category_id'); if (is_numeric($categoryId)) { $cat_tbl = JTable::getInstance('Category', 'JTable'); $cat_tbl->load($categoryId); $rgt = $cat_tbl->rgt; $lft = $cat_tbl->lft; $baselevel = (int) $cat_tbl->level; $query->where('c.lft >= '.(int) $lft); $query->where('c.rgt <= '.(int) $rgt); } elseif (is_array($categoryId)) { JArrayHelper::toInteger($categoryId); $categoryId = implode(',', $categoryId); $query->where('a.catid IN ('.$categoryId.')'); } // Filter on the level. if ($level = $this->getState('filter.level')) { $query->where('c.level <= '.((int) $level + (int) $baselevel - 1)); } // Filter by author $authorId = $this->getState('filter.author_id'); if (is_numeric($authorId)) { $type = $this->getState('filter.author_id.include', true) ? '= ' : '<>'; $query->where('a.created_by '.$type.(int) $authorId); } // Filter by search in title. $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } elseif (stripos($search, 'author:') === 0) { $search = $db->Quote('%'.$db->escape(substr($search, 7), true).'%'); $query->where('(ua.name LIKE '.$search.' OR ua.username LIKE '.$search.')'); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); $query->where('(a.title LIKE '.$search.' OR a.alias LIKE '.$search.')'); } } // Filter on the language. if ($language = $this->getState('filter.language')) { $query->where('a.language = '.$db->quote($language)); } // Add the list ordering clause. $orderCol = $this->state->get('list.ordering', 'a.title'); $orderDirn = $this->state->get('list.direction', 'asc'); if ($orderCol == 'a.ordering' || $orderCol == 'category_title') { $orderCol = 'c.title '.$orderDirn.', a.ordering'; } //sqlsrv change if($orderCol == 'language') $orderCol = 'l.title'; if($orderCol == 'access_level') $orderCol = 'ag.title'; $query->order($db->escape($orderCol.' '.$orderDirn)); // echo nl2br(str_replace('#__','jos_',$query)); return $query; } /** * Build a list of authors * * @return JDatabaseQuery * @since 1.6 */ public function getAuthors() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Construct the query $query->select('u.id AS value, u.name AS text'); $query->from('#__users AS u'); $query->join('INNER', '#__content AS c ON c.created_by = u.id'); $query->group('u.id, u.name'); $query->order('u.name'); // Setup the query $db->setQuery($query->__toString()); // Return the result return $db->loadObjectList(); } /** * Method to get a list of articles. * Overridden to add a check for access levels. * * @return mixed An array of data items on success, false on failure. * @since 1.6.1 */ public function getItems() { $items = parent::getItems(); $app = JFactory::getApplication(); if ($app->isSite()) { $user = JFactory::getUser(); $groups = $user->getAuthorisedViewLevels(); for ($x = 0, $count = count($items); $x < $count; $x++) { //Check the access level. Remove articles the user shouldn't see if (!in_array($items[$x]->access, $groups)) { unset($items[$x]); } } } return $items; } } archive.php000066600000010217151371541700006707 0ustar00state->params; // Filter on archived articles $this->setState('filter.published', 2); // Filter on month, year $this->setState('filter.month', JRequest::getInt('month')); $this->setState('filter.year', JRequest::getInt('year')); // Optional filter text $this->setState('list.filter', JRequest::getString('filter-search')); // Get list limit $app = JFactory::getApplication(); $itemid = JRequest::getInt('Itemid', 0); $limit = $app->getUserStateFromRequest('com_content.archive.list' . $itemid . '.limit', 'limit', $params->get('display_num'), 'uint'); $this->setState('list.limit', $limit); } /** * @return JDatabaseQuery */ function getListQuery() { // Set the archive ordering $params = $this->state->params; $articleOrderby = $params->get('orderby_sec', 'rdate'); $articleOrderDate = $params->get('order_date'); // No category ordering $categoryOrderby = ''; $secondary = ContentHelperQuery::orderbySecondary($articleOrderby, $articleOrderDate) . ', '; $primary = ContentHelperQuery::orderbyPrimary($categoryOrderby); $orderby = $primary . ' ' . $secondary . ' a.created DESC '; $this->setState('list.ordering', $orderby); $this->setState('list.direction', ''); // Create a new query object. $query = parent::getListQuery(); // Add routing for archive //sqlsrv changes $case_when = ' CASE WHEN '; $case_when .= $query->charLength('a.alias'); $case_when .= ' THEN '; $a_id = $query->castAsChar('a.id'); $case_when .= $query->concatenate(array($a_id, 'a.alias'), ':'); $case_when .= ' ELSE '; $case_when .= $a_id.' END as slug'; $query->select($case_when); $case_when = ' CASE WHEN '; $case_when .= $query->charLength('c.alias'); $case_when .= ' THEN '; $c_id = $query->castAsChar('c.id'); $case_when .= $query->concatenate(array($c_id, 'c.alias'), ':'); $case_when .= ' ELSE '; $case_when .= $c_id.' END as catslug'; $query->select($case_when); // Filter on month, year // First, get the date field $queryDate = ContentHelperQuery::getQueryDate($articleOrderDate); if ($month = $this->getState('filter.month')) { $query->where('MONTH('. $queryDate . ') = ' . $month); } if ($year = $this->getState('filter.year')) { $query->where('YEAR('. $queryDate . ') = ' . $year); } //echo nl2br(str_replace('#__','jos_',$query)); return $query; } /** * Method to get the archived article list * * @access public * @return array */ public function getData() { $app = JFactory::getApplication(); // Lets load the content if it doesn't already exist if (empty($this->_data)) { // Get the page/component configuration $params = $app->getParams(); // Get the pagination request variables $limit = JRequest::getUInt('limit', $params->get('display_num', 20)); $limitstart = JRequest::getUInt('limitstart', 0); $query = $this->_buildQuery(); $this->_data = $this->_getList($query, $limitstart, $limit); } return $this->_data; } // JModel override to add alternating value for $odd protected function _getList($query, $limitstart=0, $limit=0) { $result = parent::_getList($query, $limitstart, $limit); $odd = 1; foreach ($result as $k => $row) { $result[$k]->odd = $odd; $odd = 1 - $odd; } return $result; } } article.php000066600000033660151371541700006720 0ustar00getTable(); $i = 0; // Check that the category exists if ($categoryId) { $categoryTable = JTable::getInstance('Category'); if (!$categoryTable->load($categoryId)) { if ($error = $categoryTable->getError()) { // Fatal error $this->setError($error); return false; } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } } } if (empty($categoryId)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } // Check that the user has create permission for the component $extension = JFactory::getApplication()->input->get('option', ''); $user = JFactory::getUser(); if (!$user->authorise('core.create', $extension . '.category.' . $categoryId)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE')); return false; } // Parent exists so we let's proceed while (!empty($pks)) { // Pop the first ID off the stack $pk = array_shift($pks); $table->reset(); // Check that the row actually exists if (!$table->load($pk)) { if ($error = $table->getError()) { // Fatal error $this->setError($error); return false; } else { // Not fatal error $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // Alter the title & alias $data = $this->generateNewTitle($categoryId, $table->alias, $table->title); $table->title = $data['0']; $table->alias = $data['1']; // Reset the ID because we are making a copy $table->id = 0; // Reset hits because we are making a copy $table->hits = 0; // New category ID $table->catid = $categoryId; // TODO: Deal with ordering? //$table->ordering = 1; // Get the featured state $featured = $table->featured; // Check the row. if (!$table->check()) { $this->setError($table->getError()); return false; } // Store the row. if (!$table->store()) { $this->setError($table->getError()); return false; } // Get the new item ID $newId = $table->get('id'); // Add the new ID to the array $newIds[$i] = $newId; $i++; // Check if the article was featured and update the #__content_frontpage table if ($featured == 1) { $db = $this->getDbo(); $query = $db->getQuery(true); $query->insert($db->quoteName('#__content_frontpage')); $query->values($newId . ', 0'); $db->setQuery($query); $db->query(); } } // Clean the cache $this->cleanCache(); return $newIds; } /** * Method to test whether a record can be deleted. * * @param object $record A record object. * * @return boolean True if allowed to delete the record. Defaults to the permission set in the component. * @since 1.6 */ protected function canDelete($record) { if (!empty($record->id)) { if ($record->state != -2) { return ; } $user = JFactory::getUser(); return $user->authorise('core.delete', 'com_content.article.'.(int) $record->id); } } /** * Method to test whether a record can have its state edited. * * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. * @since 1.6 */ protected function canEditState($record) { $user = JFactory::getUser(); // Check for existing article. if (!empty($record->id)) { return $user->authorise('core.edit.state', 'com_content.article.'.(int) $record->id); } // New article, so check against the category. elseif (!empty($record->catid)) { return $user->authorise('core.edit.state', 'com_content.category.'.(int) $record->catid); } // Default to component settings if neither article nor category known. else { return parent::canEditState('com_content'); } } /** * Prepare and sanitise the table data prior to saving. * * @param JTable A JTable object. * * @return void * @since 1.6 */ protected function prepareTable(&$table) { // Set the publish date to now $db = $this->getDbo(); if($table->state == 1 && intval($table->publish_up) == 0) { $table->publish_up = JFactory::getDate()->toSql(); } // Increment the content version number. $table->version++; // Reorder the articles within the category so the new article is first if (empty($table->id)) { $table->reorder('catid = '.(int) $table->catid.' AND state >= 0'); } } /** * Returns a Table object, always creating it. * * @param type The table type to instantiate * @param string A prefix for the table class name. Optional. * @param array Configuration array for model. Optional. * * @return JTable A database object */ public function getTable($type = 'Content', $prefix = 'JTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } /** * Method to get a single record. * * @param integer The id of the primary key. * * @return mixed Object on success, false on failure. */ public function getItem($pk = null) { if ($item = parent::getItem($pk)) { // Convert the params field to an array. $registry = new JRegistry; $registry->loadString($item->attribs); $item->attribs = $registry->toArray(); // Convert the metadata field to an array. $registry = new JRegistry; $registry->loadString($item->metadata); $item->metadata = $registry->toArray(); // Convert the images field to an array. $registry = new JRegistry; $registry->loadString($item->images); $item->images = $registry->toArray(); // Convert the urls field to an array. $registry = new JRegistry; $registry->loadString($item->urls); $item->urls = $registry->toArray(); $item->articletext = trim($item->fulltext) != '' ? $item->introtext . "
" . $item->fulltext : $item->introtext; } return $item; } /** * Method to get the record form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * * @return mixed A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_content.article', 'article', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } $jinput = JFactory::getApplication()->input; // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first. if ($jinput->get('a_id')) { $id = $jinput->get('a_id', 0); } // The back end uses id so we use that the rest of the time and set it to 0 by default. else { $id = $jinput->get('id', 0); } // Determine correct permissions to check. if ($this->getState('article.id')) { $id = $this->getState('article.id'); // Existing record. Can only edit in selected categories. $form->setFieldAttribute('catid', 'action', 'core.edit'); // Existing record. Can only edit own articles in selected categories. $form->setFieldAttribute('catid', 'action', 'core.edit.own'); } else { // New record. Can only create in selected categories. $form->setFieldAttribute('catid', 'action', 'core.create'); } $user = JFactory::getUser(); // Check for existing article. // Modify the form based on Edit State access controls. if ($id != 0 && (!$user->authorise('core.edit.state', 'com_content.article.'.(int) $id)) || ($id == 0 && !$user->authorise('core.edit.state', 'com_content')) ) { // Disable fields for display. $form->setFieldAttribute('featured', 'disabled', 'true'); $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('publish_up', 'disabled', 'true'); $form->setFieldAttribute('publish_down', 'disabled', 'true'); $form->setFieldAttribute('state', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is an article you can edit. $form->setFieldAttribute('featured', 'filter', 'unset'); $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('publish_up', 'filter', 'unset'); $form->setFieldAttribute('publish_down', 'filter', 'unset'); $form->setFieldAttribute('state', 'filter', 'unset'); } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_content.edit.article.data', array()); if (empty($data)) { $data = $this->getItem(); // Prime some default values. if ($this->getState('article.id') == 0) { $app = JFactory::getApplication(); $data->set('catid', JRequest::getInt('catid', $app->getUserState('com_content.articles.filter.category_id'))); } } return $data; } /** * Method to save the form data. * * @param array The form data. * * @return boolean True on success. * @since 1.6 */ public function save($data) { if (isset($data['images']) && is_array($data['images'])) { $registry = new JRegistry; $registry->loadArray($data['images']); $data['images'] = (string)$registry; } if (isset($data['urls']) && is_array($data['urls'])) { $registry = new JRegistry; $registry->loadArray($data['urls']); $data['urls'] = (string)$registry; } // Alter the title for save as copy if (JRequest::getVar('task') == 'save2copy') { list($title, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']); $data['title'] = $title; $data['alias'] = $alias; } if (parent::save($data)) { if (isset($data['featured'])) { $this->featured($this->getState($this->getName().'.id'), $data['featured']); } return true; } return false; } /** * Method to toggle the featured setting of articles. * * @param array The ids of the items to toggle. * @param int The value to toggle to. * * @return boolean True on success. */ public function featured($pks, $value = 0) { // Sanitize the ids. $pks = (array) $pks; JArrayHelper::toInteger($pks); if (empty($pks)) { $this->setError(JText::_('COM_CONTENT_NO_ITEM_SELECTED')); return false; } $table = $this->getTable('Featured', 'ContentTable'); try { $db = $this->getDbo(); $db->setQuery( 'UPDATE #__content' . ' SET featured = '.(int) $value. ' WHERE id IN ('.implode(',', $pks).')' ); if (!$db->query()) { throw new Exception($db->getErrorMsg()); } if ((int)$value == 0) { // Adjust the mapping table. // Clear the existing features settings. $db->setQuery( 'DELETE FROM #__content_frontpage' . ' WHERE content_id IN ('.implode(',', $pks).')' ); if (!$db->query()) { throw new Exception($db->getErrorMsg()); } } else { // first, we find out which of our new featured articles are already featured. $query = $db->getQuery(true); $query->select('f.content_id'); $query->from('#__content_frontpage AS f'); $query->where('content_id IN ('.implode(',', $pks).')'); //echo $query; $db->setQuery($query); if (!is_array($old_featured = $db->loadColumn())) { throw new Exception($db->getErrorMsg()); } // we diff the arrays to get a list of the articles that are newly featured $new_featured = array_diff($pks, $old_featured); // Featuring. $tuples = array(); foreach ($new_featured as $pk) { $tuples[] = '('.$pk.', 0)'; } if (count($tuples)) { $db->setQuery( 'INSERT INTO #__content_frontpage ('.$db->quoteName('content_id').', '.$db->quoteName('ordering').')' . ' VALUES '.implode(',', $tuples) ); if (!$db->query()) { $this->setError($db->getErrorMsg()); return false; } } } } catch (Exception $e) { $this->setError($e->getMessage()); return false; } $table->reorder(); $this->cleanCache(); return true; } /** * A protected method to get a set of ordering conditions. * * @param object A record object. * * @return array An array of conditions to add to add to ordering queries. * @since 1.6 */ protected function getReorderConditions($table) { $condition = array(); $condition[] = 'catid = '.(int) $table->catid; return $condition; } /** * Custom clean the cache of com_content and content modules * * @since 1.6 */ protected function cleanCache($group = null, $client_id = 0) { parent::cleanCache('com_content'); parent::cleanCache('mod_articles_archive'); parent::cleanCache('mod_articles_categories'); parent::cleanCache('mod_articles_category'); parent::cleanCache('mod_articles_latest'); parent::cleanCache('mod_articles_news'); parent::cleanCache('mod_articles_popular'); } } index.html000066600000000037151371541700006551 0ustar00 contact.php000066600000027271151371541730006734 0ustar00setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; if (!empty($commands['category_id'])) { $cmd = JArrayHelper::getValue($commands, 'move_copy', 'c'); if ($cmd == 'c') { $result = $this->batchCopy($commands['category_id'], $pks, $contexts); if (is_array($result)) { $pks = $result; } else { return false; } } elseif ($cmd == 'm' && !$this->batchMove($commands['category_id'], $pks, $contexts)) { return false; } $done = true; } if (!empty($commands['assetgroup_id'])) { if (!$this->batchAccess($commands['assetgroup_id'], $pks, $contexts)) { return false; } $done = true; } if (!empty($commands['language_id'])) { if (!$this->batchLanguage($commands['language_id'], $pks, $contexts)) { return false; } $done = true; } if (strlen($commands['user_id']) > 0) { if (!$this->batchUser($commands['user_id'], $pks, $contexts)) { return false; } $done = true; } if (!$done) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } // Clear the cache $this->cleanCache(); return true; } /** * Batch copy items to a new category or current. * * @param integer $value The new category. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return mixed An array of new IDs on success, boolean false on failure. * * @since 11.1 */ protected function batchCopy($value, $pks, $contexts) { $categoryId = (int) $value; $table = $this->getTable(); $i = 0; // Check that the category exists if ($categoryId) { $categoryTable = JTable::getInstance('Category'); if (!$categoryTable->load($categoryId)) { if ($error = $categoryTable->getError()) { // Fatal error $this->setError($error); return false; } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } } } if (empty($categoryId)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_MOVE_CATEGORY_NOT_FOUND')); return false; } // Check that the user has create permission for the component $user = JFactory::getUser(); if (!$user->authorise('core.create', 'com_contact.category.' . $categoryId)) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE')); return false; } // Parent exists so we let's proceed while (!empty($pks)) { // Pop the first ID off the stack $pk = array_shift($pks); $table->reset(); // Check that the row actually exists if (!$table->load($pk)) { if ($error = $table->getError()) { // Fatal error $this->setError($error); return false; } else { // Not fatal error $this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk)); continue; } } // Alter the title & alias $data = $this->generateNewTitle($categoryId, $table->alias, $table->name); $table->name = $data['0']; $table->alias = $data['1']; // Reset the ID because we are making a copy $table->id = 0; // New category ID $table->catid = $categoryId; // TODO: Deal with ordering? //$table->ordering = 1; // Check the row. if (!$table->check()) { $this->setError($table->getError()); return false; } // Store the row. if (!$table->store()) { $this->setError($table->getError()); return false; } // Get the new item ID $newId = $table->get('id'); // Add the new ID to the array $newIds[$i] = $newId; $i++; } // Clean the cache $this->cleanCache(); return $newIds; } /** * Batch change a linked user. * * @param integer $value The new value matching a User ID. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 2.5 */ protected function batchUser($value, $pks, $contexts) { // Set the variables $user = JFactory::getUser(); $table = $this->getTable(); foreach ($pks as $pk) { if ($user->authorise('core.edit', $contexts[$pk])) { $table->reset(); $table->load($pk); $table->user_id = (int) $value; if (!$table->store()) { $this->setError($table->getError()); return false; } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Method to test whether a record can be deleted. * * @param object $record A record object. * * @return boolean True if allowed to delete the record. Defaults to the permission set in the component. * @since 1.6 */ protected function canDelete($record) { if (!empty($record->id)) { if ($record->published != -2) { return ; } $user = JFactory::getUser(); return $user->authorise('core.delete', 'com_contact.category.'.(int) $record->catid); } } /** * Method to test whether a record can have its state edited. * * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. * @since 1.6 */ protected function canEditState($record) { $user = JFactory::getUser(); // Check against the category. if (!empty($record->catid)) { return $user->authorise('core.edit.state', 'com_contact.category.'.(int) $record->catid); } // Default to component settings if category not known. else { return parent::canEditState($record); } } /** * Returns a Table object, always creating it * * @param type $type The table type to instantiate * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * * @return JTable A database object * @since 1.6 */ public function getTable($type = 'Contact', $prefix = 'ContactTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } /** * Method to get the row form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * * @return mixed A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { JForm::addFieldPath('JPATH_ADMINISTRATOR/components/com_users/models/fields'); // Get the form. $form = $this->loadForm('com_contact.contact', 'contact', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } // Modify the form based on access controls. if (!$this->canEditState((object) $data)) { // Disable fields for display. $form->setFieldAttribute('featured', 'disabled', 'true'); $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('published', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is a record you can edit. $form->setFieldAttribute('featured', 'filter', 'unset'); $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('published', 'filter', 'unset'); } return $form; } /** * Method to get a single record. * * @param integer $pk The id of the primary key. * * @return mixed Object on success, false on failure. * @since 1.6 */ public function getItem($pk = null) { if ($item = parent::getItem($pk)) { // Convert the params field to an array. $registry = new JRegistry; $registry->loadString($item->metadata); $item->metadata = $registry->toArray(); } return $item; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_contact.edit.contact.data', array()); if (empty($data)) { $data = $this->getItem(); // Prime some default values. if ($this->getState('contact.id') == 0) { $app = JFactory::getApplication(); $data->set('catid', JRequest::getInt('catid', $app->getUserState('com_contact.contacts.filter.category_id'))); } } return $data; } /** * Prepare and sanitise the table prior to saving. * * @param JTable $table * * @return void * @since 1.6 */ protected function prepareTable(&$table) { $date = JFactory::getDate(); $user = JFactory::getUser(); $table->name = htmlspecialchars_decode($table->name, ENT_QUOTES); $table->alias = JApplication::stringURLSafe($table->alias); if (empty($table->alias)) { $table->alias = JApplication::stringURLSafe($table->name); } if (empty($table->id)) { // Set the values //$table->created = $date->toSql(); // Set ordering to the last item if not set if (empty($table->ordering)) { $db = JFactory::getDbo(); $db->setQuery('SELECT MAX(ordering) FROM #__contact_details'); $max = $db->loadResult(); $table->ordering = $max+1; } } else { // Set the values //$table->modified = $date->toSql(); //$table->modified_by = $user->get('id'); } } /** * A protected method to get a set of ordering conditions. * * @param JTable $table A record object. * * @return array An array of conditions to add to add to ordering queries. * @since 1.6 */ protected function getReorderConditions($table) { $condition = array(); $condition[] = 'catid = '.(int) $table->catid; return $condition; } /** * Method to toggle the featured setting of contacts. * * @param array $pks The ids of the items to toggle. * @param int $value The value to toggle to. * * @return boolean True on success. * @since 1.6 */ public function featured($pks, $value = 0) { // Sanitize the ids. $pks = (array) $pks; JArrayHelper::toInteger($pks); if (empty($pks)) { $this->setError(JText::_('COM_CONTACT_NO_ITEM_SELECTED')); return false; } $table = $this->getTable(); try { $db = $this->getDbo(); $db->setQuery( 'UPDATE #__contact_details' . ' SET featured = '.(int) $value. ' WHERE id IN ('.implode(',', $pks).')' ); if (!$db->query()) { throw new Exception($db->getErrorMsg()); } } catch (Exception $e) { $this->setError($e->getMessage()); return false; } $table->reorder(); // Clean component's cache $this->cleanCache(); return true; } } rules/contactemailmessage.php000066600000001213151371541730012427 0ustar00get('banned_text'); foreach(explode(';', $banned) as $item){ if ($item != '' && JString::stristr($value, $item) !== false) return false; } return true; } } rules/contactemailsubject.php000066600000001216151371541730012445 0ustar00get('banned_subject'); foreach(explode(';', $banned) as $item){ if ($item != '' && JString::stristr($value, $item) !== false) return false; } return true; } } rules/contactemail.php000066600000001435151371541730011070 0ustar00get('banned_email'); foreach(explode(';', $banned) as $item){ if ($item != '' && JString::stristr($value, $item) !== false) return false; } return true; } } rules/.htaccess000066600000000177151371541730007514 0ustar00 Order allow,deny Deny from all rules/index.html000066600000000037151371541730007706 0ustar00 forms/contact.xml000066600000046074151371541730010075 0ustar00
forms/form.xml000066600000033772151371541730007406 0ustar00
sitemap.php000066600000023144151371551270006736 0ustar00setState('sitemap.id', $pk); $offset = JRequest::getInt('limitstart'); $this->setState('list.offset', $offset); // Load the parameters. $params = $app->getParams(); $this->setState('params', $params); // TODO: Tune these values based on other permissions. $this->setState('filter.published', 1); $this->setState('filter.access', true); } /** * Method to get sitemap data. * * @param integer The id of the article. * * @return mixed Menu item data object on success, false on failure. */ public function &getItem($pk = null) { // Initialize variables. $db = $this->getDbo(); $pk = (!empty($pk)) ? $pk : (int) $this->getState('sitemap.id'); // If not sitemap specified, select the default one if (!$pk) { $query = $db->getQuery(true); $query->select('id')->from('#__xmap_sitemap')->where('is_default=1'); $db->setQuery($query); $pk = $db->loadResult(); } if ($this->_item === null) { $this->_item = array(); } if (!isset($this->_item[$pk])) { try { $query = $db->getQuery(true); $query->select($this->getState('item.select', 'a.*')); $query->from('#__xmap_sitemap AS a'); $query->where('a.id = ' . (int) $pk); // Filter by published state. $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.state = ' . (int) $published); } // Filter by access level. if ($access = $this->getState('filter.access')) { $user = JFactory::getUser(); $groups = implode(',', $user->getAuthorisedViewLevels()); $query->where('a.access IN (' . $groups . ')'); } $this->_db->setQuery($query); $data = $this->_db->loadObject(); if ($error = $this->_db->getErrorMsg()) { throw new Exception($error); } if (empty($data)) { throw new Exception(JText::_('COM_XMAP_ERROR_SITEMAP_NOT_FOUND')); } // Check for published state if filter set. if (is_numeric($published) && $data->state != $published) { throw new Exception(JText::_('COM_XMAP_ERROR_SITEMAP_NOT_FOUND')); } // Convert parameter fields to objects. $registry = new JRegistry('_default'); $registry->loadString($data->attribs); $data->params = clone $this->getState('params'); $data->params->merge($registry); // Convert the selections field to an array. $registry = new JRegistry('_default'); $registry->loadString($data->selections); $data->selections = $registry->toArray(); // Compute access permissions. if ($access) { // If the access filter has been set, we already know this user can view. $data->params->set('access-view', true); } else { // If no access filter is set, the layout takes some responsibility for display of limited information. $user = &JFactory::getUser(); $groups = $user->authorisedLevels(); $data->params->set('access-view', in_array($data->access, $groups)); } // TODO: Type 2 permission checks? $this->_item[$pk] = $data; } catch (Exception $e) { $this->setError($e->getMessage()); $this->_item[$pk] = false; } } return $this->_item[$pk]; } public function getItems() { if ($item = $this->getItem()) { return XmapHelper::getMenuItems($item->selections); } return false; } function getExtensions() { return XmapHelper::getExtensions(); } /** * Increment the hit counter for the sitemap. * * @param int Optional primary key of the sitemap to increment. * * @return boolean True if successful; false otherwise and internal error set. */ public function hit($count) { // Initialize variables. $pk = (int) $this->getState('sitemap.id'); $view = JRequest::getCmd('view', 'html'); if ($view != 'xml' && $view != 'html') { return false; } $this->_db->setQuery( 'UPDATE #__xmap_sitemap' . ' SET views_' . $view . ' = views_' . $view . ' + 1, count_' . $view . ' = ' . $count . ', lastvisit_' . $view . ' = ' . JFactory::getDate()->toUnix() . ' WHERE id = ' . (int) $pk ); if (!$this->_db->query()) { $this->setError($this->_db->getErrorMsg()); return false; } return true; } public function getSitemapItems($view=null) { if (!isset($view)) { $view = JRequest::getCmd('view'); } $db = JFactory::getDBO(); $pk = (int) $this->getState('sitemap.id'); if (self::$items !== NULL && isset(self::$items[$view])) { return; } $query = "select * from #__xmap_items where view='$view' and sitemap_id=" . $pk; $db->setQuery($query); $rows = $db->loadObjectList(); self::$items[$view] = array(); foreach ($rows as $row) { self::$items[$view][$row->itemid] = array(); self::$items[$view][$row->itemid][$row->uid] = array(); $pairs = explode(';', $row->properties); foreach ($pairs as $pair) { if (strpos($pair, '=') !== FALSE) { list($property, $value) = explode('=', $pair); self::$items[$view][$row->itemid][$row->uid][$property] = $value; } } } return self::$items; } function chageItemPropery($uid, $itemid, $view, $property, $value) { $items = $this->getSitemapItems($view); $db = JFactory::getDBO(); $pk = (int) $this->getState('sitemap.id'); $isNew = false; if (empty($items[$view][$itemid][$uid])) { $items[$view][$itemid][$uid] = array(); $isNew = true; } $items[$view][$itemid][$uid][$property] = $value; $sep = $properties = ''; foreach ($items[$view][$itemid][$uid] as $k => $v) { $properties .= $sep . $k . '=' . $v; $sep = ';'; } if (!$isNew) { $query = 'UPDATE #__xmap_items SET properties=\'' . $db->escape($properties) . "' where uid='" . $db->escape($uid) . "' and itemid=$itemid and view='$view' and sitemap_id=" . $pk; } else { $query = 'INSERT #__xmap_items (uid,itemid,view,sitemap_id,properties) values ( \'' . $db->escape($uid) . "',$itemid,'$view',$pk,'" . $db->escape($properties) . "')"; } $db->setQuery($query); //echo $db->getQuery();exit; if ($db->query()) { return true; } else { return false; } } function toggleItem($uid, $itemid) { $app = JFactory::getApplication('site'); $sitemap = $this->getItem(); $displayer = new XmapDisplayer($app->getParams(), $sitemap); $excludedItems = $displayer->getExcludedItems(); if (isset($excludedItems[$itemid])) { $excludedItems[$itemid] = (array) $excludedItems[$itemid]; } if (!$displayer->isExcluded($itemid, $uid)) { $excludedItems[$itemid][] = $uid; $state = 0; } else { if (is_array($excludedItems[$itemid]) && count($excludedItems[$itemid])) { $excludedItems[$itemid] = array_filter($excludedItems[$itemid], create_function('$var', 'return ($var != \'' . $uid . '\');')); } else { unset($excludedItems[$itemid]); } $state = 1; } $registry = new JRegistry('_default'); $registry->loadArray($excludedItems); $str = $registry->toString(); $db = JFactory::getDBO(); $query = "UPDATE #__xmap_sitemap set excluded_items='" . $db->escape($str) . "' where id=" . $sitemap->id; $db->setQuery($query); $db->query(); return $state; } } export.php000066600000006044151371556550006623 0ustar00input; $db = JFactory::getDbo(); $exportfile_model = $this->_getModel('exportfile'); // Load the backend language file $lang = JFactory::getLanguage(); $lang->load('com_csvi', JPATH_ADMINISTRATOR); // Load the template $template = new CsviTemplate(); $template->load($jinput->get('template_id', 0, 'int')); $template->set('exportto', 'general', $jinput->get('exportto', 'tofront', 'cmd')); $jinput->set('template', $template); // Set the export type $jinput->set('export_type', $template->get('operation', 'options')); // Initiate the log $csvilog = new CsviLog(); // Create a new Import ID in the logger $csvilog->setId(); // Set to collect debug info $csvilog->setDebug($template->get('collect_debug_info', 'general')); // Set some log info $csvilog->SetAction('export'); $csvilog->SetActionType($template->get('export_type'), $template->getName()); // Add the logger to the registry $jinput->set('csvilog', $csvilog); // Load the fields to export $exportfields = $exportfile_model->getExportFields(); if (!empty($exportfields)) { $jinput->set('export.fields', $exportfields); // Allow big SQL selects $db->setQuery("SET OPTION SQL_BIG_SELECTS=1"); $db->query(); // Get the filename for the export file $jinput->set('export.filename', $exportfile_model->exportFilename()); // See if we need to get an XML/HTML class $export_format = $template->get('export_file', 'general'); if ($export_format == 'xml' || $export_format == 'html') { $exportclass = $exportfile_model->getExportClass(); if ($exportclass) $jinput->set('export.class', $exportclass); else { $csvilog->AddStats('incorrect', JText::_('COM_CSVI_NO_EXPORT_CLASS')); $jinput->set('logcount', 0); return false; } } // Return all is good return true; } else { $csvilog->AddStats('incorrect', JText::_('COM_CSVI_NO_EXPORT_FIELDS')); $jinput->set('logcount', 0); return false; } } /** * Create a proxy for including other models * * @copyright * @author RolandD * @todo * @see * @access private * @param * @return * @since 3.0 */ private function _getModel($model) { return $this->getInstance($model, 'CsviModel'); } }login.php000066600000006370151371573300006404 0ustar00loadForm('com_users.login', 'login', array('load_data' => $loadData)); if (empty($form)) { return false; } return $form; } /** * Method to get the data that should be injected in the form. * * @return array The default data is an empty array. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered login form data. $app = JFactory::getApplication(); $data = $app->getUserState('users.login.form.data', array()); // check for return URL from the request first if ($return = JRequest::getVar('return', '', 'method', 'base64')) { $data['return'] = base64_decode($return); if (!JURI::isInternal($data['return'])) { $data['return'] = ''; } } // Set the return URL if empty. if (!isset($data['return']) || empty($data['return'])) { $data['return'] = 'index.php?option=com_users&view=profile'; } $app->setUserState('users.login.form.data', $data); return $data; } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState() { // Get the application object. $params = JFactory::getApplication()->getParams('com_users'); // Load the parameters. $this->setState('params', $params); } /** * Method to allow derived classes to preprocess the form. * * @param object A form object. * @param mixed The data expected for the form. * @param string The name of the plugin group to import (defaults to "content"). * @throws Exception if there is an error in the form event. * @since 1.6 */ protected function preprocessForm(JForm $form, $data, $group = 'user') { // Import the approriate plugin group. JPluginHelper::importPlugin($group); // Get the dispatcher. $dispatcher = JDispatcher::getInstance(); // Trigger the form preparation event. $results = $dispatcher->trigger('onContentPrepareForm', array($form, $data)); // Check for errors encountered while preparing the form. if (count($results) && in_array(false, $results, true)) { // Get the last error. $error = $dispatcher->getError(); // Convert to a JException if necessary. if (!($error instanceof Exception)) { throw new Exception($error); } } } } reset.php000066600000026574151371573300006426 0ustar00loadForm('com_users.reset_request', 'reset_request', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } /** * Method to get the password reset complete form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return JForm A JForm object on success, false on failure * @since 1.6 */ public function getResetCompleteForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_users.reset_complete', 'reset_complete', $options = array('control' => 'jform')); if (empty($form)) { return false; } return $form; } /** * Method to get the password reset confirm form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return JForm A JForm object on success, false on failure * @since 1.6 */ public function getResetConfirmForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_users.reset_confirm', 'reset_confirm', $options = array('control' => 'jform')); if (empty($form)) { return false; } return $form; } /** * Override preprocessForm to load the user plugin group instead of content. * * @param object A form object. * @param mixed The data expected for the form. * @throws Exception if there is an error in the form event. * @since 1.6 */ protected function preprocessForm(JForm $form, $data, $group = 'user') { parent::preprocessForm($form, $data, $group); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState() { // Get the application object. $params = JFactory::getApplication()->getParams('com_users'); // Load the parameters. $this->setState('params', $params); } /** * @since 1.6 */ function processResetComplete($data) { // Get the form. $form = $this->getResetCompleteForm(); // Check for an error. if ($form instanceof Exception) { return $form; } // Filter and validate the form data. $data = $form->filter($data); $return = $form->validate($data); // Check for an error. if ($return instanceof Exception) { return $return; } // Check the validation results. if ($return === false) { // Get the validation messages from the form. foreach ($form->getErrors() as $message) { $this->setError($message); } return false; } // Get the token and user id from the confirmation process. $app = JFactory::getApplication(); $token = $app->getUserState('com_users.reset.token', null); $userId = $app->getUserState('com_users.reset.user', null); // Check the token and user id. if (empty($token) || empty($userId)) { return new JException(JText::_('COM_USERS_RESET_COMPLETE_TOKENS_MISSING'), 403); } // Get the user object. $user = JUser::getInstance($userId); // Check for a user and that the tokens match. if (empty($user) || $user->activation !== $token) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } // Make sure the user isn't blocked. if ($user->block) { $this->setError(JText::_('COM_USERS_USER_BLOCKED')); return false; } // Generate the new password hash. $password = JUserHelper::hashPassword($data['password1']); // Update the user object. $user->password = $password; $user->activation = ''; $user->password_clear = $data['password1']; // Save the user to the database. if (!$user->save(true)) { return new JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500); } // Flush the user data from the session. $app->setUserState('com_users.reset.token', null); $app->setUserState('com_users.reset.user', null); return true; } /** * @since 1.6 */ function processResetConfirm($data) { // Get the form. $form = $this->getResetConfirmForm(); // Check for an error. if ($form instanceof Exception) { return $form; } // Filter and validate the form data. $data = $form->filter($data); $return = $form->validate($data); // Check for an error. if ($return instanceof Exception) { return $return; } // Check the validation results. if ($return === false) { // Get the validation messages from the form. foreach ($form->getErrors() as $message) { $this->setError($message); } return false; } // Find the user id for the given token. $db = $this->getDbo(); $query = $db->getQuery(true); $query->select('activation'); $query->select('id'); $query->select('block'); $query->from($db->quoteName('#__users')); $query->where($db->quoteName('username').' = '.$db->Quote($data['username'])); // Get the user id. $db->setQuery((string) $query); $user = $db->loadObject(); // Check for an error. if ($db->getErrorNum()) { return new JException(JText::sprintf('COM_USERS_DATABASE_ERROR', $db->getErrorMsg()), 500); } // Check for a user. if (empty($user)) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } $parts = explode( ':', $user->activation ); $crypt = $parts[0]; if (!isset($parts[1])) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } $salt = $parts[1]; $testcrypt = JUserHelper::getCryptedPassword($data['token'], $salt); // Verify the token if (!($crypt == $testcrypt)) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } // Make sure the user isn't blocked. if ($user->block) { $this->setError(JText::_('COM_USERS_USER_BLOCKED')); return false; } // Push the user data into the session. $app = JFactory::getApplication(); $app->setUserState('com_users.reset.token', $crypt.':'.$salt); $app->setUserState('com_users.reset.user', $user->id); return true; } /** * Method to start the password reset process. * * @since 1.6 */ public function processResetRequest($data) { $config = JFactory::getConfig(); // Get the form. $form = $this->getForm(); // Check for an error. if ($form instanceof Exception) { return $form; } // Filter and validate the form data. $data = $form->filter($data); $return = $form->validate($data); // Check for an error. if ($return instanceof Exception) { return $return; } // Check the validation results. if ($return === false) { // Get the validation messages from the form. foreach ($form->getErrors() as $message) { $this->setError($message); } return false; } // Find the user id for the given email address. $db = $this->getDbo(); $query = $db->getQuery(true); $query->select('id'); $query->from($db->quoteName('#__users')); $query->where($db->quoteName('email').' = '.$db->Quote($data['email'])); // Get the user object. $db->setQuery((string) $query); $userId = $db->loadResult(); // Check for an error. if ($db->getErrorNum()) { $this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $db->getErrorMsg()), 500); return false; } // Check for a user. if (empty($userId)) { $this->setError(JText::_('COM_USERS_INVALID_EMAIL')); return false; } // Get the user object. $user = JUser::getInstance($userId); // Make sure the user isn't blocked. if ($user->block) { $this->setError(JText::_('COM_USERS_USER_BLOCKED')); return false; } // Make sure the user isn't a Super Admin. if ($user->authorise('core.admin')) { $this->setError(JText::_('COM_USERS_REMIND_SUPERADMIN_ERROR')); return false; } // Make sure the user has not exceeded the reset limit if (!$this->checkResetLimit($user)) { $resetLimit = (int) JFactory::getApplication()->getParams()->get('reset_time'); $this->setError(JText::plural('COM_USERS_REMIND_LIMIT_ERROR_N_HOURS', $resetLimit)); return false; } // Set the confirmation token. $token = JApplication::getHash(JUserHelper::genRandomPassword()); $salt = JUserHelper::getSalt('crypt-md5'); $hashedToken = md5($token.$salt).':'.$salt; $user->activation = $hashedToken; // Save the user to the database. if (!$user->save(true)) { return new JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED', $user->getError()), 500); } // Assemble the password reset confirmation link. $mode = $config->get('force_ssl', 0) == 2 ? 1 : -1; $itemid = UsersHelperRoute::getLoginRoute(); $itemid = $itemid !== null ? '&Itemid='.$itemid : ''; $link = 'index.php?option=com_users&view=reset&layout=confirm'.$itemid; // Put together the email template data. $data = $user->getProperties(); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['link_text'] = JRoute::_($link, false, $mode); $data['link_html'] = JRoute::_($link, true, $mode); $data['token'] = $token; $subject = JText::sprintf( 'COM_USERS_EMAIL_PASSWORD_RESET_SUBJECT', $data['sitename'] ); $body = JText::sprintf( 'COM_USERS_EMAIL_PASSWORD_RESET_BODY', $data['sitename'], $data['token'], $data['link_text'] ); // Send the password reset request email. $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $user->email, $subject, $body); // Check for an error. if ($return !== true) { return new JException(JText::_('COM_USERS_MAIL_FAILED'), 500); } return true; } /** * Method to check if user reset limit has been exceeded within the allowed time period. * * @param JUser the user doing the password reset * * @return boolean true if user can do the reset, false if limit exceeded * * @since 2.5 */ public function checkResetLimit($user) { $params = JFactory::getApplication()->getParams(); $maxCount = (int) $params->get('reset_count'); $resetHours = (int) $params->get('reset_time'); $result = true; $lastResetTime = strtotime($user->lastResetTime) ? strtotime($user->lastResetTime) : 0; $hoursSinceLastReset = (strtotime(JFactory::getDate()->toSql()) - $lastResetTime) / 3600; // If it's been long enough, start a new reset count if ($hoursSinceLastReset > $resetHours) { $user->lastResetTime = JFactory::getDate()->toSql(); $user->resetCount = 1; } // If we are under the max count, just increment the counter elseif ($user->resetCount < $maxCount) { $user->resetCount; } // At this point, we know we have exceeded the maximum resets for the time period else { $result = false; } return $result; } } remind.php000066600000010342151371573300006544 0ustar00loadForm('com_users.remind', 'remind', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } /** * Override preprocessForm to load the user plugin group instead of content. * * @param object A form object. * @param mixed The data expected for the form. * @throws Exception if there is an error in the form event. * @since 1.6 */ protected function preprocessForm(JForm $form, $data, $group = 'user') { parent::preprocessForm($form, $data, 'user'); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState() { // Get the application object. $app = JFactory::getApplication(); $params = $app->getParams('com_users'); // Load the parameters. $this->setState('params', $params); } /** * @since 1.6 */ public function processRemindRequest($data) { // Get the form. $form = $this->getForm(); // Check for an error. if (empty($form)) { return false; } // Validate the data. $data = $this->validate($form, $data); // Check for an error. if ($data instanceof Exception) { return $return; } // Check the validation results. if ($data === false) { // Get the validation messages from the form. foreach ($form->getErrors() as $message) { $this->setError($message); } return false; } // Find the user id for the given email address. $db = $this->getDbo(); $query = $db->getQuery(true); $query->select('*'); $query->from($db->quoteName('#__users')); $query->where($db->quoteName('email').' = '.$db->Quote($data['email'])); // Get the user id. $db->setQuery((string) $query); $user = $db->loadObject(); // Check for an error. if ($db->getErrorNum()) { $this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $db->getErrorMsg()), 500); return false; } // Check for a user. if (empty($user)) { $this->setError(JText::_('COM_USERS_USER_NOT_FOUND')); return false; } // Make sure the user isn't blocked. if ($user->block) { $this->setError(JText::_('COM_USERS_USER_BLOCKED')); return false; } $config = JFactory::getConfig(); // Assemble the login link. $itemid = UsersHelperRoute::getLoginRoute(); $itemid = $itemid !== null ? '&Itemid='.$itemid : ''; $link = 'index.php?option=com_users&view=login'.$itemid; $mode = $config->get('force_ssl', 0) == 2 ? 1 : -1; // Put together the email template data. $data = JArrayHelper::fromObject($user); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['link_text'] = JRoute::_($link, false, $mode); $data['link_html'] = JRoute::_($link, true, $mode); $subject = JText::sprintf( 'COM_USERS_EMAIL_USERNAME_REMINDER_SUBJECT', $data['sitename'] ); $body = JText::sprintf( 'COM_USERS_EMAIL_USERNAME_REMINDER_BODY', $data['sitename'], $data['username'], $data['link_text'] ); // Send the password reset request email. $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $user->email, $subject, $body); // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_MAIL_FAILED'), 500); return false; } return true; } } forms/reset_complete.xml000066600000001412151371573300011435 0ustar00
forms/remind.xml000066600000000724151371573300007706 0ustar00
forms/profile.xml000066600000003416151371573300010071 0ustar00
forms/sitelang.xml000066600000000612151371573300010232 0ustar00
forms/frontend_admin.xml000066600000001706151371573300011420 0ustar00
forms/reset_request.xml000066600000000761151371573300011323 0ustar00
forms/login.xml000066600000000777151371573300007550 0ustar00
forms/reset_confirm.xml000066600000001033151371573300011261 0ustar00
forms/registration.xml000066600000004027151371573300011142 0ustar00
forms/frontend.xml000066600000001616151371573300010250 0ustar00
registration.php000066600000034415151371573300010007 0ustar00getDbo(); // Get the user id based on the token. $db->setQuery( 'SELECT '.$db->quoteName('id').' FROM '.$db->quoteName('#__users') . ' WHERE '.$db->quoteName('activation').' = '.$db->Quote($token) . ' AND '.$db->quoteName('block').' = 1' . ' AND '.$db->quoteName('lastvisitDate').' = '.$db->Quote($db->getNullDate()) ); $userId = (int) $db->loadResult(); // Check for a valid user id. if (!$userId) { $this->setError(JText::_('COM_USERS_ACTIVATION_TOKEN_NOT_FOUND')); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Activate the user. $user = JFactory::getUser($userId); // Admin activation is on and user is verifying their email if (($userParams->get('useractivation') == 2) && !$user->getParam('activate', 0)) { $uri = JURI::getInstance(); // Compile the admin notification mail values. $data = $user->getProperties(); $data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword()); $user->set('activation', $data['activation']); $data['siteurl'] = JUri::base(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base.JRoute::_('index.php?option=com_users&task=registration.activate&token='.$data['activation'], false); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $user->setParam('activate', 1); $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACTIVATE_WITH_ADMIN_ACTIVATION_SUBJECT', $data['name'], $data['sitename'] ); $emailBody = JText::sprintf( 'COM_USERS_EMAIL_ACTIVATE_WITH_ADMIN_ACTIVATION_BODY', $data['sitename'], $data['name'], $data['email'], $data['username'], $data['activate'] ); // get all admin users $query = 'SELECT name, email, sendEmail, id' . ' FROM #__users' . ' WHERE sendEmail=1'; $db->setQuery( $query ); $rows = $db->loadObjectList(); // Send mail to all users with users creating permissions and receiving system emails foreach( $rows as $row ) { $usercreator = JFactory::getUser($id = $row->id); if ($usercreator->authorise('core.create', 'com_users')) { $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $row->email, $emailSubject, $emailBody); // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED')); return false; } } } } //Admin activation is on and admin is activating the account elseif (($userParams->get('useractivation') == 2) && $user->getParam('activate', 0)) { $user->set('activation', ''); $user->set('block', '0'); $uri = JURI::getInstance(); // Compile the user activated notification mail values. $data = $user->getProperties(); $user->setParam('activate', 0); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['siteurl'] = JUri::base(); $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACTIVATED_BY_ADMIN_ACTIVATION_SUBJECT', $data['name'], $data['sitename'] ); $emailBody = JText::sprintf( 'COM_USERS_EMAIL_ACTIVATED_BY_ADMIN_ACTIVATION_BODY', $data['name'], $data['siteurl'], $data['username'] ); $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody); // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED')); return false; } } else { $user->set('activation', ''); $user->set('block', '0'); } // Store the user object. if (!$user->save()) { $this->setError(JText::sprintf('COM_USERS_REGISTRATION_ACTIVATION_SAVE_FAILED', $user->getError())); return false; } return $user; } /** * Method to get the registration form data. * * The base form data is loaded and then an event is fired * for users plugins to extend the data. * * @return mixed Data object on success, false on failure. * @since 1.6 */ public function getData() { if ($this->data === null) { $this->data = new stdClass(); $app = JFactory::getApplication(); $params = JComponentHelper::getParams('com_users'); // Override the base user data with any data in the session. $temp = (array)$app->getUserState('com_users.registration.data', array()); foreach ($temp as $k => $v) { $this->data->$k = $v; } // Get the groups the user should be added to after registration. $this->data->groups = array(); // Get the default new user group, Registered if not specified. $system = $params->get('new_usertype', 2); $this->data->groups[] = $system; // Unset the passwords. unset($this->data->password1); unset($this->data->password2); // Get the dispatcher and load the users plugins. $dispatcher = JDispatcher::getInstance(); JPluginHelper::importPlugin('user'); // Trigger the data preparation event. $results = $dispatcher->trigger('onContentPrepareData', array('com_users.registration', $this->data)); // Check for errors encountered while preparing the data. if (count($results) && in_array(false, $results, true)) { $this->setError($dispatcher->getError()); $this->data = false; } } return $this->data; } /** * Method to get the registration form. * * The base form is loaded from XML and then an event is fired * for users plugins to extend the form with extra fields. * * @param array $data An optional array of data for the form to interogate. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return JForm A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_users.registration', 'registration', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { return $this->getData(); } /** * Override preprocessForm to load the user plugin group instead of content. * * @param object A form object. * @param mixed The data expected for the form. * @throws Exception if there is an error in the form event. * @since 1.6 */ protected function preprocessForm(JForm $form, $data, $group = 'user') { $userParams = JComponentHelper::getParams('com_users'); //Add the choice for site language at registration time if ($userParams->get('site_language') == 1 && $userParams->get('frontend_userparams') == 1) { $form->loadFile('sitelang', false); } parent::preprocessForm($form, $data, $group); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState() { // Get the application object. $app = JFactory::getApplication(); $params = $app->getParams('com_users'); // Load the parameters. $this->setState('params', $params); } /** * Method to save the form data. * * @param array The form data. * @return mixed The user id on success, false on failure. * @since 1.6 */ public function register($temp) { $config = JFactory::getConfig(); $db = $this->getDbo(); $params = JComponentHelper::getParams('com_users'); // Initialise the table with JUser. $user = new JUser; $data = (array)$this->getData(); // Merge in the registration data. foreach ($temp as $k => $v) { $data[$k] = $v; } // Prepare the data for the user object. $data['email'] = $data['email1']; $data['password'] = $data['password1']; $useractivation = $params->get('useractivation'); $sendpassword = $params->get('sendpassword', 1); // Check if the user needs to activate their account. if (($useractivation == 1) || ($useractivation == 2)) { $data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword()); $data['block'] = 1; } // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError())); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Store the data. if (!$user->save()) { $this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError())); return false; } // Compile the notification mail values. $data = $user->getProperties(); $data['fromname'] = $config->get('fromname'); $data['mailfrom'] = $config->get('mailfrom'); $data['sitename'] = $config->get('sitename'); $data['siteurl'] = JUri::root(); // Handle account activation/confirmation emails. if ($useractivation == 2) { // Set the link to confirm the user email. $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base.JRoute::_('index.php?option=com_users&task=registration.activate&token='.$data['activation'], false); $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename'] ); if ($sendpassword) { $emailBody = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username'], $data['password_clear'] ); } else { $emailBody = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username'] ); } } elseif ($useractivation == 1) { // Set the link to activate the user account. $uri = JURI::getInstance(); $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port')); $data['activate'] = $base.JRoute::_('index.php?option=com_users&task=registration.activate&token='.$data['activation'], false); $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename'] ); if ($sendpassword) { $emailBody = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username'], $data['password_clear'] ); } else { $emailBody = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY_NOPW', $data['name'], $data['sitename'], $data['activate'], $data['siteurl'], $data['username'] ); } } else { $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename'] ); $emailBody = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_BODY', $data['name'], $data['sitename'], $data['siteurl'] ); } // Send the registration email. $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $data['email'], $emailSubject, $emailBody); //Send Notification mail to administrators if (($params->get('useractivation') < 2) && ($params->get('mail_to_admin') == 1)) { $emailSubject = JText::sprintf( 'COM_USERS_EMAIL_ACCOUNT_DETAILS', $data['name'], $data['sitename'] ); $emailBodyAdmin = JText::sprintf( 'COM_USERS_EMAIL_REGISTERED_NOTIFICATION_TO_ADMIN_BODY', $data['name'], $data['username'], $data['siteurl'] ); // get all admin users $query = 'SELECT name, email, sendEmail' . ' FROM #__users' . ' WHERE sendEmail=1'; $db->setQuery( $query ); $rows = $db->loadObjectList(); // Send mail to all superadministrators id foreach( $rows as $row ) { $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $row->email, $emailSubject, $emailBodyAdmin); // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED')); return false; } } } // Check for an error. if ($return !== true) { $this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED')); // Send a system message to administrators receiving system mails $db = JFactory::getDBO(); $q = "SELECT id FROM #__users WHERE block = 0 AND sendEmail = 1"; $db->setQuery($q); $sendEmail = $db->loadColumn(); if (count($sendEmail) > 0) { $jdate = new JDate(); // Build the query to add the messages $q = "INSERT INTO ".$db->quoteName('#__messages')." (".$db->quoteName('user_id_from'). ", ".$db->quoteName('user_id_to').", ".$db->quoteName('date_time'). ", ".$db->quoteName('subject').", ".$db->quoteName('message').") VALUES "; $messages = array(); foreach ($sendEmail as $userid) { $messages[] = "(".$userid.", ".$userid.", '".$jdate->toSql()."', '".JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT')."', '".JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY', $return, $data['username'])."')"; } $q .= implode(',', $messages); $db->setQuery($q); $db->query(); } return false; } if ($useractivation == 1) return "useractivate"; elseif ($useractivation == 2) return "adminactivate"; else return $user->id; } } profile.php000066600000017027151371573300006735 0ustar00getState('user.id'); if ($userId) { // Initialise the table with JUser. $table = JTable::getInstance('User'); // Attempt to check the row in. if (!$table->checkin($userId)) { $this->setError($table->getError()); return false; } } return true; } /** * Method to check out a user for editing. * * @param integer The id of the row to check out. * @return boolean True on success, false on failure. * @since 1.6 */ public function checkout($userId = null) { // Get the user id. $userId = (!empty($userId)) ? $userId : (int)$this->getState('user.id'); if ($userId) { // Initialise the table with JUser. $table = JTable::getInstance('User'); // Get the current user object. $user = JFactory::getUser(); // Attempt to check the row out. if (!$table->checkout($user->get('id'), $userId)) { $this->setError($table->getError()); return false; } } return true; } /** * Method to get the profile form data. * * The base form data is loaded and then an event is fired * for users plugins to extend the data. * * @return mixed Data object on success, false on failure. * @since 1.6 */ public function getData() { if ($this->data === null) { $userId = $this->getState('user.id'); // Initialise the table with JUser. $this->data = new JUser($userId); // Set the base user data. $this->data->email1 = $this->data->get('email'); $this->data->email2 = $this->data->get('email'); // Override the base user data with any data in the session. $temp = (array)JFactory::getApplication()->getUserState('com_users.edit.profile.data', array()); foreach ($temp as $k => $v) { $this->data->$k = $v; } // Unset the passwords. unset($this->data->password1); unset($this->data->password2); $registry = new JRegistry($this->data->params); $this->data->params = $registry->toArray(); // Get the dispatcher and load the users plugins. $dispatcher = JDispatcher::getInstance(); JPluginHelper::importPlugin('user'); // Trigger the data preparation event. $results = $dispatcher->trigger('onContentPrepareData', array('com_users.profile', $this->data)); // Check for errors encountered while preparing the data. if (count($results) && in_array(false, $results, true)) { $this->setError($dispatcher->getError()); $this->data = false; } } return $this->data; } /** * Method to get the profile form. * * The base form is loaded from XML and then an event is fired * for users plugins to extend the form with extra fields. * * @param array $data An optional array of data for the form to interogate. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return JForm A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_users.profile', 'profile', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } // Check for username compliance and parameter set $isUsernameCompliant = true; if ($this->loadFormData()->username) { $username = $this->loadFormData()->username; $isUsernameCompliant = !(preg_match('#[<>"\'%;()&\\\\]|\\.\\./#', $username) || strlen(utf8_decode($username)) < 2 || trim($username) != $username); } $this->setState('user.username.compliant', $isUsernameCompliant); if (!JComponentHelper::getParams('com_users')->get('change_login_name') && $isUsernameCompliant) { $form->setFieldAttribute('username', 'class', ''); $form->setFieldAttribute('username', 'filter', ''); $form->setFieldAttribute('username', 'description', 'COM_USERS_PROFILE_NOCHANGE_USERNAME_DESC'); $form->setFieldAttribute('username', 'validate', ''); $form->setFieldAttribute('username', 'message', ''); $form->setFieldAttribute('username', 'readonly', 'true'); $form->setFieldAttribute('username', 'required', 'false'); } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { return $this->getData(); } /** * Override preprocessForm to load the user plugin group instead of content. * * @param object A form object. * @param mixed The data expected for the form. * @throws Exception if there is an error in the form event. * @since 1.6 */ protected function preprocessForm(JForm $form, $data, $group = 'user') { if (JComponentHelper::getParams('com_users')->get('frontend_userparams')) { $form->loadFile('frontend', false); if (JFactory::getUser()->authorise('core.login.admin')) { $form->loadFile('frontend_admin', false); } } parent::preprocessForm($form, $data, $group); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState() { // Get the application object. $params = JFactory::getApplication()->getParams('com_users'); // Get the user id. $userId = JFactory::getApplication()->getUserState('com_users.edit.profile.id'); $userId = !empty($userId) ? $userId : (int)JFactory::getUser()->get('id'); // Set the user id. $this->setState('user.id', $userId); // Load the parameters. $this->setState('params', $params); } /** * Method to save the form data. * * @param array The form data. * @return mixed The user id on success, false on failure. * @since 1.6 */ public function save($data) { $userId = (!empty($data['id'])) ? $data['id'] : (int)$this->getState('user.id'); $user = new JUser($userId); // Prepare the data for the user object. $data['email'] = $data['email1']; $data['password'] = $data['password1']; // Unset the username if it should not be overwritten $username = $data['username']; $isUsernameCompliant = $this->getState('user.username.compliant'); if (!JComponentHelper::getParams('com_users')->get('change_login_name') && $isUsernameCompliant) { unset($data['username']); } // Unset the block so it does not get overwritten unset($data['block']); // Unset the sendEmail so it does not get overwritten unset($data['sendEmail']); // Bind the data. if (!$user->bind($data)) { $this->setError(JText::sprintf('COM_USERS_PROFILE_BIND_FAILED', $user->getError())); return false; } // Load the users plugin group. JPluginHelper::importPlugin('user'); // Null the user groups so they don't get overwritten $user->groups = null; // Store the data. if (!$user->save()) { $this->setError($user->getError()); return false; } return $user->id; } } contacts.php000066600000015257151372057020007113 0ustar00context .= '.'.$layout; } $search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search'); $this->setState('filter.search', $search); $access = $this->getUserStateFromRequest($this->context.'.filter.access', 'filter_access', 0, 'int'); $this->setState('filter.access', $access); $published = $this->getUserStateFromRequest($this->context.'.filter.published', 'filter_published', ''); $this->setState('filter.published', $published); $categoryId = $this->getUserStateFromRequest($this->context.'.filter.category_id', 'filter_category_id'); $this->setState('filter.category_id', $categoryId); $language = $this->getUserStateFromRequest($this->context.'.filter.language', 'filter_language', ''); $this->setState('filter.language', $language); // List state information. parent::populateState('a.name', 'asc'); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. * @since 1.6 */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.search'); $id .= ':'.$this->getState('filter.access'); $id .= ':'.$this->getState('filter.published'); $id .= ':'.$this->getState('filter.category_id'); $id .= ':'.$this->getState('filter.language'); return parent::getStoreId($id); } /** * Build an SQL query to load the list data. * * @return JDatabaseQuery * @since 1.6 */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); $user = JFactory::getUser(); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.id, a.name, a.alias, a.checked_out, a.checked_out_time, a.catid, a.user_id' . ', a.published, a.access, a.created, a.created_by, a.ordering, a.featured, a.language'. ', a.publish_up, a.publish_down' ) ); $query->from('#__contact_details AS a'); // Join over the users for the linked user. $query->select('ul.name AS linked_user'); $query->join('LEFT', '#__users AS ul ON ul.id=a.user_id'); // Join over the language $query->select('l.title AS language_title'); $query->join('LEFT', $db->quoteName('#__languages').' AS l ON l.lang_code = a.language'); // Join over the users for the checked out user. $query->select('uc.name AS editor'); $query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out'); // Join over the asset groups. $query->select('ag.title AS access_level'); $query->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access'); // Join over the categories. $query->select('c.title AS category_title'); $query->join('LEFT', '#__categories AS c ON c.id = a.catid'); // Filter by access level. if ($access = $this->getState('filter.access')) { $query->where('a.access = ' . (int) $access); } // Implement View Level Access if (!$user->authorise('core.admin')) { $groups = implode(',', $user->getAuthorisedViewLevels()); $query->where('a.access IN ('.$groups.')'); } // Filter by published state $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.published = ' . (int) $published); } elseif ($published === '') { $query->where('(a.published = 0 OR a.published = 1)'); } // Filter by a single or group of categories. $categoryId = $this->getState('filter.category_id'); if (is_numeric($categoryId)) { $query->where('a.catid = '.(int) $categoryId); } elseif (is_array($categoryId)) { JArrayHelper::toInteger($categoryId); $categoryId = implode(',', $categoryId); $query->where('a.catid IN ('.$categoryId.')'); } // Filter by search in name. $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } elseif (stripos($search, 'author:') === 0) { $search = $db->Quote('%'.$db->escape(substr($search, 7), true).'%'); $query->where('(uc.name LIKE '.$search.' OR uc.username LIKE '.$search.')'); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); $query->where('(a.name LIKE '.$search.' OR a.alias LIKE '.$search.')'); } } // Filter on the language. if ($language = $this->getState('filter.language')) { $query->where('a.language = '.$db->quote($language)); } // Add the list ordering clause. $orderCol = $this->state->get('list.ordering', 'a.name'); $orderDirn = $this->state->get('list.direction', 'asc'); if ($orderCol == 'a.ordering' || $orderCol == 'category_title') { $orderCol = 'c.title '.$orderDirn.', a.ordering'; } $query->order($db->escape($orderCol.' '.$orderDirn)); //echo nl2br(str_replace('#__','jos_',$query)); return $query; } } fields/index.html000066600000000037151372057020010015 0ustar00 fields/modal/contacts.php000066600000004723151372057020011451 0ustar00id.'(id, name, object) {'; $script[] = ' document.id("'.$this->id.'_id").value = id;'; $script[] = ' document.id("'.$this->id.'_name").value = name;'; $script[] = ' SqueezeBox.close();'; $script[] = ' }'; // Add the script to the document head. JFactory::getDocument()->addScriptDeclaration(implode("\n", $script)); // Get the title of the linked chart $db = JFactory::getDBO(); $db->setQuery( 'SELECT name' . ' FROM #__contact_details' . ' WHERE id = '.(int) $this->value ); $title = $db->loadResult(); if ($error = $db->getErrorMsg()) { JError::raiseWarning(500, $error); } if (empty($title)) { $title = JText::_('COM_CONTACT_SELECT_A_CONTACT'); } $link = 'index.php?option=com_contact&view=contacts&layout=modal&tmpl=component&function=jSelectChart_'.$this->id; $html = "\n".'
'; $html .= ''."\n"; // The active contact id field. if (0 == (int)$this->value) { $value = ''; } else { $value = (int)$this->value; } // class='required' for client side validation $class = ''; if ($this->required) { $class = ' class="required modal-value"'; } $html .= ''; return $html; } } fields/modal/.htaccess000066600000000177151372057020010717 0ustar00 Order allow,deny Deny from all fields/modal/index.html000066600000000037151372057020011111 0ustar00 fields/ordering.php000066600000004215151372057020010344 0ustar00element['class'] ? ' class="'.(string) $this->element['class'].'"' : ''; $attr .= ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : ''; $attr .= $this->element['size'] ? ' size="'.(int) $this->element['size'].'"' : ''; // Initialize JavaScript field attributes. $attr .= $this->element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : ''; // Get some field values from the form. $pluginId = (int) $this->form->getValue('extension_id'); $folder = $this->form->getValue('folder'); $db = JFactory::getDbo(); // Build the query for the ordering list. $query = 'SELECT ordering AS value, name AS text, type AS type, folder AS folder, extension_id AS extension_id' . ' FROM #__extensions' . ' WHERE (type =' .$db->Quote('plugin'). 'AND folder='. $db->Quote($folder) . ')'. ' ORDER BY ordering'; // Create a read-only list (no name) with a hidden input to store the value. if ((string) $this->element['readonly'] == 'true') { $html[] = JHtml::_('list.ordering', '', $query, trim($attr), $this->value, $pluginId ? 0 : 1); $html[] = ''; } // Create a regular list. else { $html[] = JHtml::_('list.ordering', $this->name, $query, trim($attr), $this->value, $pluginId ? 0 : 1); } return implode($html); } } fields/.htaccess000066600000000177151372057020007623 0ustar00 Order allow,deny Deny from all cache.php000066600000007342151372062250006335 0ustar00getUserStateFromRequest($this->context.'.filter.client_id', 'filter_client_id', 0, 'int'); $this->setState('clientId', $clientId == 1 ? 1 : 0); $client = JApplicationHelper::getClientInfo($clientId); $this->setState('client', $client); parent::populateState('group', 'asc'); } /** * Method to get cache data * * @return array */ public function getData() { if (empty($this->_data)) { $cache = $this->getCache(); $data = $cache->getAll(); if ($data != false) { $this->_data = $data; $this->_total = count($data); if ($this->_total) { // Apply custom ordering $ordering = $this->getState('list.ordering'); $direction = ($this->getState('list.direction') == 'asc') ? 1 : -1; jimport('joomla.utilities.arrayhelper'); $this->_data = JArrayHelper::sortObjects($data, $ordering, $direction); // Apply custom pagination if ($this->_total > $this->getState('list.limit') && $this->getState('list.limit')) { $this->_data = array_slice($this->_data, $this->getState('list.start'), $this->getState('list.limit')); } } } else { $this->_data = array(); } } return $this->_data; } /** * Method to get cache instance * * @return object */ public function getCache() { $conf = JFactory::getConfig(); $options = array( 'defaultgroup' => '', 'storage' => $conf->get('cache_handler', ''), 'caching' => true, 'cachebase' => ($this->getState('clientId') == 1) ? JPATH_ADMINISTRATOR . '/cache' : $conf->get('cache_path', JPATH_SITE . '/cache') ); $cache = JCache::getInstance('', $options); return $cache; } /** * Method to get client data * * @return array */ public function getClient() { return $this->getState('client'); } /** * Get the number of current Cache Groups * * @return int */ public function getTotal() { if (empty($this->_total)) { $this->_total = count($this->getData()); } return $this->_total; } /** * Method to get a pagination object for the cache * * @return integer */ public function getPagination() { if (empty($this->_pagination)) { jimport('joomla.html.pagination'); $this->_pagination = new JPagination($this->getTotal(), $this->getState('list.start'), $this->getState('list.limit')); } return $this->_pagination; } /** * Clean out a cache group as named by param. * If no param is passed clean all cache groups. * * @param String $group */ public function clean($group = '') { $cache = $this->getCache(); $cache->clean($group); } public function cleanlist($array) { foreach ($array as $group) { $this->clean($group); } } public function purge() { $cache = JFactory::getCache(''); return $cache->gc(); } } list.php000066600000010466151372062300006242 0ustar00setState('folder', $folder); $parent = str_replace("\\", "/", dirname($folder)); $parent = ($parent == '.') ? null : $parent; $this->setState('parent', $parent); $set = true; } return parent::getState($property, $default); } function getImages() { $list = $this->getList(); return $list['images']; } function getFolders() { $list = $this->getList(); return $list['folders']; } function getDocuments() { $list = $this->getList(); return $list['docs']; } /** * Build imagelist * * @param string $listFolder The image directory to display * @since 1.5 */ function getList() { static $list; // Only process the list once per request if (is_array($list)) { return $list; } // Get current path from request $current = $this->getState('folder'); // If undefined, set to empty if ($current == 'undefined') { $current = ''; } // Initialise variables. if (strlen($current) > 0) { $basePath = COM_MEDIA_BASE.'/'.$current; } else { $basePath = COM_MEDIA_BASE; } $mediaBase = str_replace(DIRECTORY_SEPARATOR, '/', COM_MEDIA_BASE.'/'); $images = array (); $folders = array (); $docs = array (); $fileList = false; $folderList = false; if (file_exists($basePath)) { // Get the list of files and folders from the given folder $fileList = JFolder::files($basePath); $folderList = JFolder::folders($basePath); } // Iterate over the files if they exist if ($fileList !== false) { foreach ($fileList as $file) { if (is_file($basePath.'/'.$file) && substr($file, 0, 1) != '.' && strtolower($file) !== 'index.html') { $tmp = new JObject(); $tmp->name = $file; $tmp->title = $file; $tmp->path = str_replace(DIRECTORY_SEPARATOR, '/', JPath::clean($basePath . '/' . $file)); $tmp->path_relative = str_replace($mediaBase, '', $tmp->path); $tmp->size = filesize($tmp->path); $ext = strtolower(JFile::getExt($file)); switch ($ext) { // Image case 'jpg': case 'png': case 'gif': case 'xcf': case 'odg': case 'bmp': case 'jpeg': case 'ico': $info = @getimagesize($tmp->path); $tmp->width = @$info[0]; $tmp->height = @$info[1]; $tmp->type = @$info[2]; $tmp->mime = @$info['mime']; if (($info[0] > 60) || ($info[1] > 60)) { $dimensions = MediaHelper::imageResize($info[0], $info[1], 60); $tmp->width_60 = $dimensions[0]; $tmp->height_60 = $dimensions[1]; } else { $tmp->width_60 = $tmp->width; $tmp->height_60 = $tmp->height; } if (($info[0] > 16) || ($info[1] > 16)) { $dimensions = MediaHelper::imageResize($info[0], $info[1], 16); $tmp->width_16 = $dimensions[0]; $tmp->height_16 = $dimensions[1]; } else { $tmp->width_16 = $tmp->width; $tmp->height_16 = $tmp->height; } $images[] = $tmp; break; // Non-image document default: $tmp->icon_32 = "media/mime-icon-32/".$ext.".png"; $tmp->icon_16 = "media/mime-icon-16/".$ext.".png"; $docs[] = $tmp; break; } } } } // Iterate over the folders if they exist if ($folderList !== false) { foreach ($folderList as $folder) { $tmp = new JObject(); $tmp->name = basename($folder); $tmp->path = str_replace(DIRECTORY_SEPARATOR, '/', JPath::clean($basePath . '/' . $folder)); $tmp->path_relative = str_replace($mediaBase, '', $tmp->path); $count = MediaHelper::countFiles($tmp->path); $tmp->files = $count[0]; $tmp->folders = $count[1]; $folders[] = $tmp; } } $list = array('folders' => $folders, 'docs' => $docs, 'images' => $images); return $list; } } manager.php000066600000007260151372062300006677 0ustar00setState('folder', $folder); $fieldid = JRequest::getCmd('fieldid', ''); $this->setState('field.id', $fieldid); $parent = str_replace("\\", "/", dirname($folder)); $parent = ($parent == '.') ? null : $parent; $this->setState('parent', $parent); $set = true; } return parent::getState($property, $default); } /** * Image Manager Popup * * @param string $listFolder The image directory to display * @since 1.5 */ function getFolderList($base = null) { // Get some paths from the request if (empty($base)) { $base = COM_MEDIA_BASE; } //corrections for windows paths $base = str_replace(DIRECTORY_SEPARATOR, '/', $base); $com_media_base_uni = str_replace(DIRECTORY_SEPARATOR, '/', COM_MEDIA_BASE); // Get the list of folders jimport('joomla.filesystem.folder'); $folders = JFolder::folders($base, '.', true, true); $document = JFactory::getDocument(); $document->setTitle(JText::_('COM_MEDIA_INSERT_IMAGE')); // Build the array of select options for the folder list $options[] = JHtml::_('select.option', "", "/"); foreach ($folders as $folder) { $folder = str_replace($com_media_base_uni, "", str_replace(DIRECTORY_SEPARATOR, '/', $folder)); $value = substr($folder, 1); $text = str_replace(DIRECTORY_SEPARATOR, "/", $folder); $options[] = JHtml::_('select.option', $value, $text); } // Sort the folder list array if (is_array($options)) { sort($options); } // Get asset and author id (use integer filter) $input = JFactory::getApplication()->input; $asset = $input->get('asset', 0, 'integer'); $author = $input->get('author', 0, 'integer'); // Create the drop-down folder select list $list = JHtml::_('select.genericlist', $options, 'folderlist', 'class="inputbox" size="1" onchange="ImageManager.setFolder(this.options[this.selectedIndex].value, '.$asset.', '.$author.')" ', 'value', 'text', $base); return $list; } function getFolderTree($base = null) { // Get some paths from the request if (empty($base)) { $base = COM_MEDIA_BASE; } $mediaBase = str_replace(DIRECTORY_SEPARATOR, '/', COM_MEDIA_BASE.'/'); // Get the list of folders jimport('joomla.filesystem.folder'); $folders = JFolder::folders($base, '.', true, true); $tree = array(); foreach ($folders as $folder) { $folder = str_replace(DIRECTORY_SEPARATOR, '/', $folder); $name = substr($folder, strrpos($folder, '/') + 1); $relative = str_replace($mediaBase, '', $folder); $absolute = $folder; $path = explode('/', $relative); $node = (object) array('name' => $name, 'relative' => $relative, 'absolute' => $absolute); $tmp = &$tree; for ($i=0, $n=count($path); $i<$n; $i++) { if (!isset($tmp['children'])) { $tmp['children'] = array(); } if ($i == $n-1) { // We need to place the node $tmp['children'][$relative] = array('data' =>$node, 'children' => array()); break; } if (array_key_exists($key = implode('/', array_slice($path, 0, $i+1)), $tmp['children'])) { $tmp = &$tmp['children'][$key]; } } } $tree['data'] = (object) array('name' => JText::_('COM_MEDIA_MEDIA'), 'relative' => '', 'absolute' => $base); return $tree; } } help.php000066600000006416151372062610006223 0ustar00help_search)) { $this->help_search = JRequest::getString('helpsearch'); } return $this->help_search; } /** * Method to get the page * @return string page */ function &getPage() { if (is_null($this->page)) { $page = JRequest::getCmd('page', 'JHELP_START_HERE'); $this->page = JHelp::createUrl($page); } return $this->page; } /** * Method to get the lang tag * @return string lang iso tag */ function &getLangTag() { if (is_null($this->lang_tag)) { $lang = JFactory::getLanguage(); $this->lang_tag = $lang->getTag(); jimport('joomla.filesystem.folder'); if (!JFolder::exists(JPATH_BASE . '/help/' . $this->lang_tag)) { $this->lang_tag = 'en-GB'; // use english as fallback } } return $this->lang_tag; } /** * Method to get the toc * @return array Table of contents */ function &getToc() { if (is_null($this->toc)) { // Get vars $lang_tag = $this->getLangTag(); $help_search = $this->getHelpSearch(); // Get Help files $files = JFolder::files(JPATH_BASE . '/help/' . $lang_tag, '\.xml$|\.html$'); $this->toc = array(); foreach($files as $file) { $buffer = file_get_contents(JPATH_BASE . '/help/' . $lang_tag . '/' . $file); if (preg_match('#(.*?)#', $buffer, $m)) { $title = trim($m[1]); if ($title) { // Translate the page title $title = JText::_($title); // strip the extension $file = preg_replace('#\.xml$|\.html$#', '', $file); if ($help_search) { if (JString::strpos(JString::strtolower(strip_tags($buffer)), JString::strtolower($help_search)) !== false) { // Add an item in the Table of Contents $this->toc[$file] = $title; } } else { // Add an item in the Table of Contents $this->toc[$file] = $title; } } } } // Sort the Table of Contents asort($this->toc); } return $this->toc; } /** * Method to get the latest version check; * @return string Latest Version Check URL */ function &getLatestVersionCheck() { if (!$this->latest_version_check) { $override = 'http://help.joomla.org/proxy/index.php?option=com_help&keyref=Help{major}{minor}:Joomla_Version_{major}_{minor}_{maintenance}'; $this->latest_version_check = JHelp::createUrl('JVERSION', false, $override); } return $this->latest_version_check; } } sysinfo.php000066600000017241151372062610006763 0ustar00php_settings)) { $this->php_settings = array(); $this->php_settings['safe_mode'] = ini_get('safe_mode') == '1'; $this->php_settings['display_errors'] = ini_get('display_errors') == '1'; $this->php_settings['short_open_tag'] = ini_get('short_open_tag') == '1'; $this->php_settings['file_uploads'] = ini_get('file_uploads') == '1'; $this->php_settings['magic_quotes_gpc'] = ini_get('magic_quotes_gpc') == '1'; $this->php_settings['register_globals'] = ini_get('register_globals') == '1'; $this->php_settings['output_buffering'] = (bool) ini_get('output_buffering'); $this->php_settings['open_basedir'] = ini_get('open_basedir'); $this->php_settings['session.save_path'] = ini_get('session.save_path'); $this->php_settings['session.auto_start'] = ini_get('session.auto_start'); $this->php_settings['disable_functions'] = ini_get('disable_functions'); $this->php_settings['xml'] = extension_loaded('xml'); $this->php_settings['zlib'] = extension_loaded('zlib'); $this->php_settings['zip'] = function_exists('zip_open') && function_exists('zip_read'); $this->php_settings['mbstring'] = extension_loaded('mbstring'); $this->php_settings['iconv'] = function_exists('iconv'); } return $this->php_settings; } /** * method to get the config * * @return array config values */ function &getConfig() { if (is_null($this->config)) { $registry = new JRegistry(new JConfig); $this->config = $registry->toArray(); $hidden = array('host', 'user', 'password', 'ftp_user', 'ftp_pass', 'smtpuser', 'smtppass'); foreach($hidden as $key) { $this->config[$key] = 'xxxxxx'; } } return $this->config; } /** * method to get the system information * * @return array system information values */ function &getInfo() { if (is_null($this->info)) { $this->info = array(); $version = new JVersion(); $platform = new JPlatform(); $db = JFactory::getDBO(); if (isset($_SERVER['SERVER_SOFTWARE'])) { $sf = $_SERVER['SERVER_SOFTWARE']; } else { $sf = getenv('SERVER_SOFTWARE'); } $this->info['php'] = php_uname(); $this->info['dbversion'] = $db->getVersion(); $this->info['dbcollation'] = $db->getCollation(); $this->info['phpversion'] = phpversion(); $this->info['server'] = $sf; $this->info['sapi_name'] = php_sapi_name(); $this->info['version'] = $version->getLongVersion(); $this->info['platform'] = $platform->getLongVersion(); $this->info['useragent'] = $_SERVER['HTTP_USER_AGENT']; } return $this->info; } /** * method to get the PHP info * * @return string PHP info */ function &getPHPInfo() { if (is_null($this->php_info)) { ob_start(); date_default_timezone_set('UTC'); phpinfo(INFO_GENERAL | INFO_CONFIGURATION | INFO_MODULES); $phpinfo = ob_get_contents(); ob_end_clean(); preg_match_all('#]*>(.*)#siU', $phpinfo, $output); $output = preg_replace('#]*>#', '', $output[1][0]); $output = preg_replace('#(\w),(\w)#', '\1, \2', $output); $output = preg_replace('#
#', '', $output); $output = str_replace('
', '', $output); $output = preg_replace('#
(.*)<\/tr>#', '$1', $output); $output = str_replace('
', '', $output); $output = str_replace('', '', $output); $this->php_info = $output; } return $this->php_info; } /** * method to get the directory states * * @return array states of directories */ public function getDirectory() { if (is_null($this->directories)) { $this->directories = array(); $registry = JFactory::getConfig(); jimport('joomla.filesystem.folder'); $cparams = JComponentHelper::getParams('com_media'); $this->_addDirectory('administrator/components', JPATH_ADMINISTRATOR.'/components'); $this->_addDirectory('administrator/language', JPATH_ADMINISTRATOR.'/language'); // List all admin languages $admin_langs = JFolder::folders(JPATH_ADMINISTRATOR.'/language'); foreach($admin_langs as $alang) { $this->_addDirectory('administrator/language/' . $alang, JPATH_ADMINISTRATOR.'/language/'.$alang); } // List all manifests folders $manifests = JFolder::folders(JPATH_ADMINISTRATOR.'/manifests'); foreach($manifests as $_manifest) { $this->_addDirectory('administrator/manifests/' . $_manifest, JPATH_ADMINISTRATOR.'/manifests/'.$_manifest); } $this->_addDirectory('administrator/modules', JPATH_ADMINISTRATOR.'/modules'); $this->_addDirectory('administrator/templates', JPATH_THEMES); $this->_addDirectory('components', JPATH_SITE.'/components'); $this->_addDirectory($cparams->get('image_path'), JPATH_SITE.'/'.$cparams->get('image_path')); $image_folders = JFolder::folders(JPATH_SITE.'/'.$cparams->get('image_path')); // List all images folders foreach ($image_folders as $folder) { $this->_addDirectory('images/' . $folder, JPATH_SITE.'/'.$cparams->get('image_path').'/'.$folder); } $this->_addDirectory('language', JPATH_SITE.'/language'); // List all site languages $site_langs = JFolder::folders(JPATH_SITE . '/language'); foreach ($site_langs as $slang) { $this->_addDirectory('language/' . $slang, JPATH_SITE.'/language/'.$slang); } $this->_addDirectory('libraries', JPATH_LIBRARIES); $this->_addDirectory('media', JPATH_SITE.'/media'); $this->_addDirectory('modules', JPATH_SITE.'/modules'); $this->_addDirectory('plugins', JPATH_PLUGINS); $plugin_groups = JFolder::folders(JPATH_PLUGINS); foreach ($plugin_groups as $folder) { $this->_addDirectory('plugins/' . $folder, JPATH_PLUGINS.'/'.$folder); } $this->_addDirectory('templates', JPATH_SITE.'/templates'); $this->_addDirectory('configuration.php', JPATH_CONFIGURATION.'/configuration.php'); $this->_addDirectory('cache', JPATH_SITE.'/cache', 'COM_ADMIN_CACHE_DIRECTORY'); $this->_addDirectory('administrator/cache', JPATH_CACHE, 'COM_ADMIN_CACHE_DIRECTORY'); $this->_addDirectory($registry->get('log_path', JPATH_ROOT . '/log'), $registry->get('log_path', JPATH_ROOT.'/log'), 'COM_ADMIN_LOG_DIRECTORY'); $this->_addDirectory($registry->get('tmp_path', JPATH_ROOT . '/tmp'), $registry->get('tmp_path', JPATH_ROOT.'/tmp'), 'COM_ADMIN_TEMP_DIRECTORY'); } return $this->directories; } private function _addDirectory($name, $path, $message = '') { $this->directories[$name] = array('writable' => is_writable($path), 'message' => $message); } /** * method to get the editor * * @return string the default editor * * has to be removed (it is present in the config...) */ function &getEditor() { if (is_null($this->editor)) { $config = JFactory::getConfig(); $this->editor = $config->get('editor'); } return $this->editor; } } feature.php000066600000002250151372065470006725 0ustar00id.'(id, title, catid, object) {'; $script[] = ' document.id("'.$this->id.'_id").value = id;'; $script[] = ' document.id("'.$this->id.'_name").value = title;'; $script[] = ' SqueezeBox.close();'; $script[] = ' }'; // Add the script to the document head. JFactory::getDocument()->addScriptDeclaration(implode("\n", $script)); // Setup variables for display. $html = array(); $link = 'index.php?option=com_content&view=articles&layout=modal&tmpl=component&function=jSelectArticle_'.$this->id; $db = JFactory::getDBO(); $db->setQuery( 'SELECT title' . ' FROM #__content' . ' WHERE id = '.(int) $this->value ); $title = $db->loadResult(); if ($error = $db->getErrorMsg()) { JError::raiseWarning(500, $error); } if (empty($title)) { $title = JText::_('COM_CONTENT_SELECT_AN_ARTICLE'); } $title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); // The current user display field. $html[] = '
'; $html[] = ' '; $html[] = '
'; // The user select button. $html[] = '
'; $html[] = ' '; $html[] = '
'; // The active article id field. if (0 == (int)$this->value) { $value = ''; } else { $value = (int)$this->value; } // class='required' for client side validation $class = ''; if ($this->required) { $class = ' class="required modal-value"'; } $html[] = ''; return implode("\n", $html); } } update.php000066600000015045151372075200006552 0ustar00setState('message', $app->getUserState('com_installer.message')); $this->setState('extension_message', $app->getUserState('com_installer.extension_message')); $app->setUserState('com_installer.message', ''); $app->setUserState('com_installer.extension_message', ''); parent::populateState('name', 'asc'); } /** * Method to get the database query * * @return JDatabaseQuery The database query * @since 1.6 */ protected function getListQuery() { $db = $this->getDbo(); $query = $db->getQuery(true); // grab updates ignoring new installs $query->select('*')->from('#__updates')->where('extension_id != 0'); $query->order($this->getState('list.ordering').' '.$this->getState('list.direction')); // Filter by extension_id if ($eid = $this->getState('filter.extension_id')) { $query->where($db->nq('extension_id') . ' = ' . $db->q((int) $eid)); } else { $query->where($db->nq('extension_id').' != '.$db->q(0)); $query->where($db->nq('extension_id').' != '.$db->q(700)); } return $query; } /** * Finds updates for an extension. * * @param int Extension identifier to look for * @return boolean Result * @since 1.6 */ public function findUpdates($eid=0, $cache_timeout = 0) { $updater = JUpdater::getInstance(); $results = $updater->findUpdates($eid, $cache_timeout); return true; } /** * Removes all of the updates from the table. * * @return boolean result of operation * @since 1.6 */ public function purge() { $db = JFactory::getDBO(); // Note: TRUNCATE is a DDL operation // This may or may not mean depending on your database $db->setQuery('TRUNCATE TABLE #__updates'); if ($db->Query()) { // Reset the last update check timestamp $query = $db->getQuery(true); $query->update($db->nq('#__update_sites')); $query->set($db->nq('last_check_timestamp').' = '.$db->q(0)); $db->setQuery($query); $db->query(); $this->_message = JText::_('COM_INSTALLER_PURGED_UPDATES'); return true; } else { $this->_message = JText::_('COM_INSTALLER_FAILED_TO_PURGE_UPDATES'); return false; } } /** * Enables any disabled rows in #__update_sites table * * @return boolean result of operation * @since 1.6 */ public function enableSites() { $db = JFactory::getDBO(); $db->setQuery('UPDATE #__update_sites SET enabled = 1 WHERE enabled = 0'); if ($db->Query()) { if ($rows = $db->getAffectedRows()) { $this->_message .= JText::plural('COM_INSTALLER_ENABLED_UPDATES', $rows); } return true; } else { $this->_message .= JText::_('COM_INSTALLER_FAILED_TO_ENABLE_UPDATES'); return false; } } /** * Update function. * * Sets the "result" state with the result of the operation. * * @param Array[int] List of updates to apply * @since 1.6 */ public function update($uids) { $result = true; foreach($uids as $uid) { $update = new JUpdate(); $instance = JTable::getInstance('update'); $instance->load($uid); $update->loadFromXML($instance->detailsurl); // install sets state and enqueues messages $res = $this->install($update); if ($res) { $instance->delete($uid); } $result = $res & $result; } // Set the final state $this->setState('result', $result); } /** * Handles the actual update installation. * * @param JUpdate An update definition * @return boolean Result of install * @since 1.6 */ private function install($update) { $app = JFactory::getApplication(); if (isset($update->get('downloadurl')->_data)) { $url = trim($update->downloadurl->_data); } else { JError::raiseWarning('', JText::_('COM_INSTALLER_INVALID_EXTENSION_UPDATE')); return false; } $p_file = JInstallerHelper::downloadPackage($url); // Was the package downloaded? if (!$p_file) { JError::raiseWarning('', JText::sprintf('COM_INSTALLER_PACKAGE_DOWNLOAD_FAILED', $url)); return false; } $config = JFactory::getConfig(); $tmp_dest = $config->get('tmp_path'); // Unpack the downloaded package file $package = JInstallerHelper::unpack($tmp_dest . '/' . $p_file); // Get an installer instance $installer = JInstaller::getInstance(); $update->set('type', $package['type']); // Install the package if (!$installer->update($package['dir'])) { // There was an error updating the package $msg = JText::sprintf('COM_INSTALLER_MSG_UPDATE_ERROR', JText::_('COM_INSTALLER_TYPE_TYPE_'.strtoupper($package['type']))); $result = false; } else { // Package updated successfully $msg = JText::sprintf('COM_INSTALLER_MSG_UPDATE_SUCCESS', JText::_('COM_INSTALLER_TYPE_TYPE_'.strtoupper($package['type']))); $result = true; } // Quick change $this->type = $package['type']; // Set some model state values $app->enqueueMessage($msg); // TODO: Reconfigure this code when you have more battery life left $this->setState('name', $installer->get('name')); $this->setState('result', $result); $app->setUserState('com_installer.message', $installer->message); $app->setUserState('com_installer.extension_message', $installer->get('extension_message')); // Cleanup the install files if (!is_file($package['packagefile'])) { $config = JFactory::getConfig(); $package['packagefile'] = $config->get('tmp_path') . '/' . $package['packagefile']; } JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']); return $result; } } fields/search.php000066600000002207151372075200007777 0ustar00name . '" id="' . $this->id . '" value="' . htmlspecialchars($this->value) . '" title="' . JText::_('JSEARCH_FILTER') . '" onchange="this.form.submit();" />'; $html.= ''; $html.= ''; return $html; } } fields/client.php000066600000002216151372075200010010 0ustar00element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : ''; $options = array(); foreach ($this->element->children() as $option) { $options[] = JHtml::_('select.option', $option->attributes('value'), JText::_(trim($option->data()))); } $options[] = JHtml::_('select.option', '0', JText::sprintf('JSITE')); $options[] = JHtml::_('select.option', '1', JText::sprintf('JADMINISTRATOR')); $return = JHtml::_('select.genericlist', $options, $this->name, $onchange, 'value', 'text', $this->value, $this->id); return $return; } } fields/group.php000066600000002663151372075200007674 0ustar00element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : ''; $options = array(); foreach ($this->element->children() as $option) { $options[] = JHtml::_('select.option', (string)$option->attributes()->value, JText::_(trim((string) $option))); } $dbo = JFactory::getDbo(); $query = $dbo->getQuery(true); $query->select('DISTINCT folder'); $query->from('#__extensions'); $query->where('folder != '.$dbo->quote('')); $query->order('folder'); $dbo->setQuery((string)$query); $folders = $dbo->loadColumn(); foreach($folders as $folder) { $options[] = JHtml::_('select.option', $folder, $folder); } $return = JHtml::_('select.genericlist', $options, $this->name, $onchange, 'value', 'text', $this->value, $this->id); return $return; } } fields/type.php000066600000002557151372075200007523 0ustar00element['onchange'] ? ' onchange="'.(string) $this->element['onchange'].'"' : ''; $options = array(); foreach ($this->element->children() as $option) { $options[] = JHtml::_('select.option', $option->attributes('value'), JText::_(trim((string) $option))); } $db = JFactory::getDBO(); $query = $db->getQuery(true); $query->select('type')->from('#__extensions'); $db->setQuery($query); $types = array_unique($db->loadColumn()); foreach($types as $type) { $options[] = JHtml::_('select.option', $type, JText::_('COM_INSTALLER_TYPE_'. strtoupper($type))); } $return = JHtml::_('select.genericlist', $options, $this->name, $onchange, 'value', 'text', $this->value, $this->id); return $return; } } manage.php000066600000021630151372075200006515 0ustar00getUserState($this->context.'.data'); $filters = $data['filters']; } else { $app->setUserState($this->context.'.data', array('filters'=>$filters)); } $this->setState('message', $app->getUserState('com_installer.message')); $this->setState('extension_message', $app->getUserState('com_installer.extension_message')); $app->setUserState('com_installer.message', ''); $app->setUserState('com_installer.extension_message', ''); $this->setState('filter.search', isset($filters['search']) ? $filters['search'] : ''); $this->setState('filter.status', isset($filters['status']) ? $filters['status'] : ''); $this->setState('filter.type', isset($filters['type']) ? $filters['type'] : ''); $this->setState('filter.group', isset($filters['group']) ? $filters['group'] : ''); $this->setState('filter.client_id', isset($filters['client_id']) ? $filters['client_id'] : ''); parent::populateState('name', 'asc'); } /** * Enable/Disable an extension. * * @return boolean True on success * @since 1.5 */ function publish(&$eid = array(), $value = 1) { // Initialise variables. $user = JFactory::getUser(); if ($user->authorise('core.edit.state', 'com_installer')) { $result = true; /* * Ensure eid is an array of extension ids * TODO: If it isn't an array do we want to set an error and fail? */ if (!is_array($eid)) { $eid = array($eid); } // Get a database connector $db = JFactory::getDBO(); // Get a table object for the extension type $table = JTable::getInstance('Extension'); JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_templates/tables'); // Enable the extension in the table and store it in the database foreach($eid as $i=>$id) { $table->load($id); if ($table->type == 'template') { $style = JTable::getInstance('Style', 'TemplatesTable'); if ($style->load(array('template' => $table->element, 'client_id' => $table->client_id, 'home'=>1))) { JError::raiseNotice(403, JText::_('COM_INSTALLER_ERROR_DISABLE_DEFAULT_TEMPLATE_NOT_PERMITTED')); unset($eid[$i]); continue; } } if ($table->protected == 1) { $result = false; JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')); } else { $table->enabled = $value; } if (!$table->store()) { $this->setError($table->getError()); $result = false; } } } else { $result = false; JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')); } return $result; } /** * Refreshes the cached manifest information for an extension. * * @param int extension identifier (key in #__extensions) * @return boolean result of refresh * @since 1.6 */ function refresh($eid) { if (!is_array($eid)) { $eid = array($eid => 0); } // Get a database connector $db = JFactory::getDBO(); // Get an installer object for the extension type $installer = JInstaller::getInstance(); $row = JTable::getInstance('extension'); $result = 0; // Uninstall the chosen extensions foreach($eid as $id) { $result|= $installer->refreshManifestCache($id); } return $result; } /** * Remove (uninstall) an extension * * @param array An array of identifiers * @return boolean True on success * @since 1.5 */ function remove($eid = array()) { // Initialise variables. $user = JFactory::getUser(); if ($user->authorise('core.delete', 'com_installer')) { // Initialise variables. $failed = array(); /* * Ensure eid is an array of extension ids in the form id => client_id * TODO: If it isn't an array do we want to set an error and fail? */ if (!is_array($eid)) { $eid = array($eid => 0); } // Get a database connector $db = JFactory::getDBO(); // Get an installer object for the extension type $installer = JInstaller::getInstance(); $row = JTable::getInstance('extension'); // Uninstall the chosen extensions foreach($eid as $id) { $id = trim($id); $row->load($id); if ($row->type) { $result = $installer->uninstall($row->type, $id); // Build an array of extensions that failed to uninstall if ($result === false) { $failed[] = $id; } } else { $failed[] = $id; } } $langstring = 'COM_INSTALLER_TYPE_TYPE_'. strtoupper($row->type); $rowtype = JText::_($langstring); if(strpos($rowtype, $langstring) !== false) { $rowtype = $row->type; } if (count($failed)) { // There was an error in uninstalling the package $msg = JText::sprintf('COM_INSTALLER_UNINSTALL_ERROR', $rowtype); $result = false; } else { // Package uninstalled sucessfully $msg = JText::sprintf('COM_INSTALLER_UNINSTALL_SUCCESS', $rowtype); $result = true; } $app = JFactory::getApplication(); $app->enqueueMessage($msg); $this->setState('action', 'remove'); $this->setState('name', $installer->get('name')); $app->setUserState('com_installer.message', $installer->message); $app->setUserState('com_installer.extension_message', $installer->get('extension_message')); return $result; } else { $result = false; JError::raiseWarning(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED')); } } /** * Method to get the database query * * @return JDatabaseQuery The database query * @since 1.6 */ protected function getListQuery() { $status = $this->getState('filter.status'); $type = $this->getState('filter.type'); $client = $this->getState('filter.client_id'); $group = $this->getState('filter.group'); $query = JFactory::getDBO()->getQuery(true); $query->select('*'); $query->select('2*protected+(1-protected)*enabled as status'); $query->from('#__extensions'); $query->where('state=0'); if ($status != '') { if ($status == '2') { $query->where('protected = 1'); } else { $query->where('protected = 0'); $query->where('enabled=' . intval($status)); } } if ($type) { $query->where('type=' . $this->_db->Quote($type)); } if ($client != '') { $query->where('client_id=' . intval($client)); } if ($group != '' && in_array($type, array('plugin', 'library', ''))) { $query->where('folder=' . $this->_db->Quote($group == '*' ? '' : $group)); } // Filter by search in id $search = $this->getState('filter.search'); if (!empty($search) && stripos($search, 'id:') === 0) { $query->where('extension_id = '.(int) substr($search, 3)); } return $query; } /** * Method to get the row form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return mixed A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Get the form. $app = JFactory::getApplication(); JForm::addFormPath(JPATH_COMPONENT . '/models/forms'); JForm::addFieldPath(JPATH_COMPONENT . '/models/fields'); $form = JForm::getInstance('com_installer.manage', 'manage', array('load_data' => $loadData)); // Check for an error. if ($form == false) { $this->setError($form->getMessage()); return false; } // Check the session for previously entered form data. $data = $this->loadFormData(); // Bind the form data if present. if (!empty($data)) { $form->bind($data); } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_installer.manage.data', array()); return $data; } } warnings.php000066600000007422151372075200007120 0ustar00JText::_('COM_INSTALLER_MSG_WARNINGS_FILEUPLOADSDISABLED'), 'description'=>JText::_('COM_INSTALLER_MSG_WARNINGS_FILEUPLOADISDISABLEDDESC')); } $upload_dir = ini_get('upload_tmp_dir'); if (!$upload_dir) { $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTSET'), 'description'=>JText::_('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTSETDESC')); } else { if (!is_writeable($upload_dir)) { $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTWRITEABLE'), 'description'=>JText::sprintf('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTWRITEABLEDESC', $upload_dir)); } } $config = JFactory::getConfig(); $tmp_path = $config->get('tmp_path'); if (!$tmp_path) { $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_JOOMLATMPNOTSET'), 'description'=>JText::_('COM_INSTALLER_MSG_WARNINGS_JOOMLATMPNOTSETDESC')); } else { if (!is_writeable($tmp_path)) { $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_JOOMLATMPNOTWRITEABLE'), 'description'=>JText::sprintf('COM_INSTALLER_MSG_WARNINGS_JOOMLATMPNOTWRITEABLEDESC', $tmp_path)); } } $memory_limit = $this->return_bytes(ini_get('memory_limit')); if ($memory_limit < (8 * 1024 * 1024) && $memory_limit != -1) { // 8MB $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_LOWMEMORYWARN'), 'description'=>JText::_('COM_INSTALLER_MSG_WARNINGS_LOWMEMORYDESC')); } elseif ($memory_limit < (16 * 1024 * 1024) && $memory_limit != -1) { //16MB $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_MEDMEMORYWARN'), 'description'=>JText::_('COM_INSTALLER_MSG_WARNINGS_MEDMEMORYDESC')); } $post_max_size = $this->return_bytes(ini_get('post_max_size')); $upload_max_filesize = $this->return_bytes(ini_get('upload_max_filesize')); if($post_max_size < $upload_max_filesize) { $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_UPLOADBIGGERTHANPOST'), 'description'=>JText::_('COM_INSTALLER_MSG_WARNINGS_UPLOADBIGGERTHANPOSTDESC')); } if($post_max_size < (4 * 1024 * 1024)) // 4MB { $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLPOSTSIZE'), 'description'=>JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLPOSTSIZEDESC')); } if($upload_max_filesize < (4 * 1024 * 1024)) // 4MB { $messages[] = array('message'=>JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLUPLOADSIZE'), 'description'=>JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLUPLOADSIZEDESC')); } return $messages; } } database.php000066600000013000151372075200007021 0ustar00setState('message', $app->getUserState('com_installer.message')); $this->setState('extension_message', $app->getUserState('com_installer.extension_message')); $app->setUserState('com_installer.message', ''); $app->setUserState('com_installer.extension_message', ''); parent::populateState('name', 'asc'); } /** * * Fixes database problems */ public function fix() { $changeSet = $this->getItems(); $changeSet->fix(); $this->fixSchemaVersion($changeSet); $this->fixUpdateVersion(); $installer = new joomlaInstallerScript(); $installer->deleteUnexistingFiles(); $this->fixDefaultTextFilters(); } /** * * Gets the changeset object * * @return JSchemaChangeset */ public function getItems() { $folder = JPATH_ADMINISTRATOR . '/components/com_admin/sql/updates/'; $changeSet = JSchemaChangeset::getInstance(JFactory::getDbo(), $folder); return $changeSet; } public function getPagination() { return true; } /** * Get version from #__schemas table * * @return mixed the return value from the query, or null if the query fails * @throws Exception */ public function getSchemaVersion() { $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('version_id')->from($db->qn('#__schemas')) ->where('extension_id = 700'); $db->setQuery($query); $result = $db->loadResult(); if ($db->getErrorNum()) { throw new Exception('Database error - getSchemaVersion'); } return $result; } /** * Fix schema version if wrong * * @param JSchemaChangeSet * * @return mixed string schema version if success, false if fail */ public function fixSchemaVersion($changeSet) { // Get correct schema version -- last file in array $schema = $changeSet->getSchema(); $db = JFactory::getDbo(); $result = false; // Check value. If ok, don't do update $version = $this->getSchemaVersion(); if ($version == $schema) { $result = $version; } else { // Delete old row $query = $db->getQuery(true); $query->delete($db->qn('#__schemas')); $query->where($db->qn('extension_id') . ' = 700'); $db->setQuery($query); $db->query(); // Add new row $query = $db->getQuery(true); $query->insert($db->qn('#__schemas')); $query->set($db->qn('extension_id') . '= 700'); $query->set($db->qn('version_id') . '= ' . $db->q($schema)); $db->setQuery($query); if ($db->query()) { $result = $schema; } } return $result; } /** * Get current version from #__extensions table * * @return mixed version if successful, false if fail */ public function getUpdateVersion() { $table = JTable::getInstance('Extension'); $table->load('700'); $cache = new JRegistry($table->manifest_cache); return $cache->get('version'); } /** * Fix Joomla version in #__extensions table if wrong (doesn't equal JVersion short version) * * @return mixed string update version if success, false if fail */ public function fixUpdateVersion() { $table = JTable::getInstance('Extension'); $table->load('700'); $cache = new JRegistry($table->manifest_cache); $updateVersion = $cache->get('version'); $cmsVersion = new JVersion(); if ($updateVersion == $cmsVersion->getShortVersion()) { return $updateVersion; } else { $cache->set('version', $cmsVersion->getShortVersion()); $table->manifest_cache = $cache->toString(); if ($table->store()) { return $cmsVersion->getShortVersion(); } else { return false; } } } /** * For version 2.5.x only * Check if com_config parameters are blank. * * @return string default text filters (if any) */ public function getDefaultTextFilters() { $table = JTable::getInstance('Extension'); $table->load($table->find(array('name' => 'com_config'))); return $table->params; } /** * For version 2.5.x only * Check if com_config parameters are blank. If so, populate with com_content text filters. * * @return mixed boolean true if params are updated, null otherwise */ public function fixDefaultTextFilters() { $table = JTable::getInstance('Extension'); $table->load($table->find(array('name' => 'com_config'))); // Check for empty $config and non-empty content filters if (!$table->params) { // Get filters from com_content and store if you find them $contentParams = JComponentHelper::getParams('com_content'); if ($contentParams->get('filters')) { $newParams = new JRegistry(); $newParams->set('filters', $contentParams->get('filters')); $table->params = (string) $newParams; $table->store(); return true; } } } } discover.php000066600000007724151372075200007113 0ustar00setState('message', $app->getUserState('com_installer.message')); $this->setState('extension_message', $app->getUserState('com_installer.extension_message')); $app->setUserState('com_installer.message', ''); $app->setUserState('com_installer.extension_message', ''); parent::populateState('name', 'asc'); } /** * Method to get the database query. * * @return JDatabaseQuery the database query * @since 1.6 */ protected function getListQuery() { $db = JFactory::getDBO(); $query = $db->getQuery(true); $query->select('*'); $query->from('#__extensions'); $query->where('state=-1'); return $query; } /** * Discover extensions. * * Finds uninstalled extensions * * @since 1.6 */ function discover() { $installer = JInstaller::getInstance(); $results = $installer->discover(); // Get all templates, including discovered ones $query = 'SELECT extension_id, element, folder, client_id, type FROM #__extensions'; $dbo = JFactory::getDBO(); $dbo->setQuery($query); $installedtmp = $dbo->loadObjectList(); $extensions = array(); foreach($installedtmp as $install) { $key = implode(':', array($install->type, $install->element, $install->folder, $install->client_id)); $extensions[$key] = $install; } unset($installedtmp); foreach($results as $result) { // check if we have a match on the element $key = implode(':', array($result->type, $result->element, $result->folder, $result->client_id)); if(!array_key_exists($key, $extensions)) { $result->store(); // put it into the table } } } /** * Installs a discovered extension. * * @since 1.6 */ function discover_install() { $app = JFactory::getApplication(); $installer = JInstaller::getInstance(); $eid = JRequest::getVar('cid', 0); if (is_array($eid) || $eid) { if (!is_array($eid)) { $eid = array($eid); } JArrayHelper::toInteger($eid); $app = JFactory::getApplication(); $failed = false; foreach($eid as $id) { $result = $installer->discover_install($id); if (!$result) { $failed = true; $app->enqueueMessage(JText::_('COM_INSTALLER_MSG_DISCOVER_INSTALLFAILED').': '. $id); } } $this->setState('action', 'remove'); $this->setState('name', $installer->get('name')); $app->setUserState('com_installer.message', $installer->message); $app->setUserState('com_installer.extension_message', $installer->get('extension_message')); if (!$failed) { $app->enqueueMessage(JText::_('COM_INSTALLER_MSG_DISCOVER_INSTALLSUCCESSFUL')); } } else { $app->enqueueMessage(JText::_('COM_INSTALLER_MSG_DISCOVER_NOEXTENSIONSELECTED')); } } /** * Cleans out the list of discovered extensions. * * @since 1.6 */ function purge() { $db = JFactory::getDBO(); $query = $db->getQuery(true); $query->delete(); $query->from('#__extensions'); $query->where('state = -1'); $db->setQuery((string)$query); if ($db->Query()) { $this->_message = JText::_('COM_INSTALLER_MSG_DISCOVER_PURGEDDISCOVEREDEXTENSIONS'); return true; } else { $this->_message = JText::_('COM_INSTALLER_MSG_DISCOVER_FAILEDTOPURGEEXTENSIONS'); return false; } } } forms/manage.xml000066600000002454151372075200007657 0ustar00
install.php000066600000015723151372075200006741 0ustar00setState('message', $app->getUserState('com_installer.message')); $this->setState('extension_message', $app->getUserState('com_installer.extension_message')); $app->setUserState('com_installer.message', ''); $app->setUserState('com_installer.extension_message', ''); // Recall the 'Install from Directory' path. $path = $app->getUserStateFromRequest($this->_context.'.install_directory', 'install_directory', $app->getCfg('tmp_path')); $this->setState('install.directory', $path); parent::populateState(); } /** * Install an extension from either folder, url or upload. * * @return boolean result of install * @since 1.5 */ function install() { $this->setState('action', 'install'); // Set FTP credentials, if given. JClientHelper::setCredentialsFromRequest('ftp'); $app = JFactory::getApplication(); switch(JRequest::getWord('installtype')) { case 'folder': // Remember the 'Install from Directory' path. $app->getUserStateFromRequest($this->_context.'.install_directory', 'install_directory'); $package = $this->_getPackageFromFolder(); break; case 'upload': $package = $this->_getPackageFromUpload(); break; case 'url': $package = $this->_getPackageFromUrl(); break; default: $app->setUserState('com_installer.message', JText::_('COM_INSTALLER_NO_INSTALL_TYPE_FOUND')); return false; break; } // Was the package unpacked? if (!$package) { $app->setUserState('com_installer.message', JText::_('COM_INSTALLER_UNABLE_TO_FIND_INSTALL_PACKAGE')); return false; } // Get an installer instance $installer = JInstaller::getInstance(); // Install the package if (!$installer->install($package['dir'])) { // There was an error installing the package $msg = JText::sprintf('COM_INSTALLER_INSTALL_ERROR', JText::_('COM_INSTALLER_TYPE_TYPE_'.strtoupper($package['type']))); $result = false; } else { // Package installed sucessfully $msg = JText::sprintf('COM_INSTALLER_INSTALL_SUCCESS', JText::_('COM_INSTALLER_TYPE_TYPE_'.strtoupper($package['type']))); $result = true; } // Set some model state values $app = JFactory::getApplication(); $app->enqueueMessage($msg); $this->setState('name', $installer->get('name')); $this->setState('result', $result); $app->setUserState('com_installer.message', $installer->message); $app->setUserState('com_installer.extension_message', $installer->get('extension_message')); $app->setUserState('com_installer.redirect_url', $installer->get('redirect_url')); // Cleanup the install files if (!is_file($package['packagefile'])) { $config = JFactory::getConfig(); $package['packagefile'] = $config->get('tmp_path') . '/' . $package['packagefile']; } JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']); return $result; } /** * Works out an installation package from a HTTP upload * * @return package definition or false on failure */ protected function _getPackageFromUpload() { // Get the uploaded file information $userfile = JRequest::getVar('install_package', null, 'files', 'array'); // Make sure that file uploads are enabled in php if (!(bool) ini_get('file_uploads')) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLFILE')); return false; } // Make sure that zlib is loaded so that the package can be unpacked if (!extension_loaded('zlib')) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLZLIB')); return false; } // If there is no uploaded file, we have a problem... if (!is_array($userfile)) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_NO_FILE_SELECTED')); return false; } // Check if there was a problem uploading the file. if ($userfile['error'] || $userfile['size'] < 1) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR')); return false; } // Build the appropriate paths $config = JFactory::getConfig(); $tmp_dest = $config->get('tmp_path') . '/' . $userfile['name']; $tmp_src = $userfile['tmp_name']; // Move uploaded file jimport('joomla.filesystem.file'); $uploaded = JFile::upload($tmp_src, $tmp_dest); // Unpack the downloaded package file $package = JInstallerHelper::unpack($tmp_dest); return $package; } /** * Install an extension from a directory * * @return Package details or false on failure * @since 1.5 */ protected function _getPackageFromFolder() { // Get the path to the package to install $p_dir = JRequest::getString('install_directory'); $p_dir = JPath::clean($p_dir); // Did you give us a valid directory? if (!is_dir($p_dir)) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_PLEASE_ENTER_A_PACKAGE_DIRECTORY')); return false; } // Detect the package type $type = JInstallerHelper::detectType($p_dir); // Did you give us a valid package? if (!$type) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_PATH_DOES_NOT_HAVE_A_VALID_PACKAGE')); return false; } $package['packagefile'] = null; $package['extractdir'] = null; $package['dir'] = $p_dir; $package['type'] = $type; return $package; } /** * Install an extension from a URL * * @return Package details or false on failure * @since 1.5 */ protected function _getPackageFromUrl() { // Get a database connector $db = JFactory::getDbo(); // Get the URL of the package to install $url = JRequest::getString('install_url'); // Did you give us a URL? if (!$url) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_ENTER_A_URL')); return false; } // Download the package at the URL given $p_file = JInstallerHelper::downloadPackage($url); // Was the package downloaded? if (!$p_file) { JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_INVALID_URL')); return false; } $config = JFactory::getConfig(); $tmp_dest = $config->get('tmp_path'); // Unpack the downloaded package file $package = JInstallerHelper::unpack($tmp_dest . '/' . $p_file); return $package; } } extension.php000066600000011516151372075200007303 0ustar00getState('list.ordering'); $search = $this->getState('filter.search'); // Replace slashes so preg_match will work $search = str_replace('/', ' ', $search); $db = $this->getDbo(); if ($ordering == 'name' || (!empty($search) && stripos($search, 'id:') !== 0)) { $db->setQuery($query); $result = $db->loadObjectList(); $lang = JFactory::getLanguage(); $this->translate($result); if (!empty($search)) { foreach($result as $i=>$item) { if (!preg_match("/$search/i", $item->name)) { unset($result[$i]); } } } JArrayHelper::sortObjects($result, $this->getState('list.ordering'), $this->getState('list.direction') == 'desc' ? -1 : 1, true, $lang->getLocale()); $total = count($result); $this->cache[$this->getStoreId('getTotal')] = $total; if ($total < $limitstart) { $limitstart = 0; $this->setState('list.start', 0); } return array_slice($result, $limitstart, $limit ? $limit : null); } else { $query->order($db->quoteName($ordering) . ' ' . $this->getState('list.direction')); $result = parent::_getList($query, $limitstart, $limit); $this->translate($result); return $result; } } /** * Translate a list of objects * * @param array The array of objects * @return array The array of translated objects */ private function translate(&$items) { $lang = JFactory::getLanguage(); foreach($items as &$item) { if (strlen($item->manifest_cache)) { $data = json_decode($item->manifest_cache); if ($data) { foreach($data as $key => $value) { if ($key == 'type') { // ignore the type field continue; } $item->$key = $value; } } } $item->author_info = @$item->authorEmail .'
'. @$item->authorUrl; $item->client = $item->client_id ? JText::_('JADMINISTRATOR') : JText::_('JSITE'); $path = $item->client_id ? JPATH_ADMINISTRATOR : JPATH_SITE; switch ($item->type) { case 'component': $extension = $item->element; $source = JPATH_ADMINISTRATOR . '/components/' . $extension; $lang->load("$extension.sys", JPATH_ADMINISTRATOR, null, false, true) || $lang->load("$extension.sys", $source, null, false, true); break; case 'file': $extension = 'files_' . $item->element; $lang->load("$extension.sys", JPATH_SITE, null, false, true); break; case 'library': $extension = 'lib_' . $item->element; $lang->load("$extension.sys", JPATH_SITE, null, false, true); break; case 'module': $extension = $item->element; $source = $path . '/modules/' . $extension; $lang->load("$extension.sys", $path, null, false, true) || $lang->load("$extension.sys", $source, null, false, true); break; case 'package': $extension = $item->element; $lang->load("$extension.sys", JPATH_SITE, null, false, true); break; case 'plugin': $extension = 'plg_' . $item->folder . '_' . $item->element; $source = JPATH_PLUGINS . '/' . $item->folder . '/' . $item->element; $lang->load("$extension.sys", JPATH_ADMINISTRATOR, null, false, true) || $lang->load("$extension.sys", $source, null, false, true); break; case 'template': $extension = 'tpl_' . $item->element; $source = $path . '/templates/' . $item->element; $lang->load("$extension.sys", $path, null, false, true) || $lang->load("$extension.sys", $source, null, false, true); break; } if (!in_array($item->type, array('language', 'template', 'library'))) { $item->name = JText::_($item->name); } settype($item->description, 'string'); if (!in_array($item->type, array('language'))) { $item->description = JText::_($item->description); } } } } languages.php000066600000012441151372075200007233 0ustar00getUserStateFromRequest($this->context.'.search', 'filter_search'); $this->setState('filter.search', $search); $accessId = $this->getUserStateFromRequest($this->context.'.access', 'filter_access', null, 'int'); $this->setState('filter.access', $accessId); $published = $this->getUserStateFromRequest($this->context.'.published', 'filter_published', ''); $this->setState('filter.published', $published); // Load the parameters. $params = JComponentHelper::getParams('com_languages'); $this->setState('params', $params); // List state information. parent::populateState('a.title', 'asc'); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. * @since 1.6 */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.search'); $id .= ':'.$this->getState('filter.access'); $id .= ':'.$this->getState('filter.published'); return parent::getStoreId($id); } /** * Method to build an SQL query to load the list data. * * @return string An SQL query * @since 1.6 */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select all fields from the languages table. $query->select($this->getState('list.select', 'a.*', 'l.home')); $query->from($db->quoteName('#__languages').' AS a'); // Join over the asset groups. $query->select('ag.title AS access_level'); $query->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access'); // Select the language home pages $query->select('l.home AS home'); $query->join('LEFT', $db->quoteName('#__menu') . ' AS l ON l.language = a.lang_code AND l.home=1 AND l.language <> ' . $db->quote('*')); // Filter on the published state. $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.published = '.(int) $published); } elseif ($published === '') { $query->where('(a.published IN (0, 1))'); } // Filter by search in title $search = $this->getState('filter.search'); if (!empty($search)) { $search = $db->Quote('%'.$db->escape($search, true).'%', false); $query->where('(a.title LIKE '.$search.')'); } // Filter by access level. if ($access = $this->getState('filter.access')) { $query->where('a.access = '.(int) $access); } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.ordering')).' '.$db->escape($this->getState('list.direction', 'ASC'))); return $query; } /** * Set the published language(s) * * @param array $cid An array of language IDs. * @param int $value The value of the published state. * * @return boolean True on success, false otherwise. * @since 1.6 */ public function setPublished($cid, $value = 0) { return JTable::getInstance('Language')->publish($cid, $value); } /** * Method to delete records. * * @param array An array of item primary keys. * * @return boolean Returns true on success, false on failure. * @since 1.6 */ public function delete($pks) { // Sanitize the array. $pks = (array) $pks; // Get a row instance. $table = JTable::getInstance('Language'); // Iterate the items to delete each one. foreach ($pks as $itemId) { if (!$table->delete((int) $itemId)) { $this->setError($table->getError()); return false; } } // Clean the cache. $this->cleanCache(); return true; } /** * Custom clean cache method, 2 places for 2 clients * * @since 1.6 */ protected function cleanCache($group = null, $client_id = 0) { parent::cleanCache('_system'); parent::cleanCache('com_languages'); } } newsfeeds.php000066600000014015151372075430007254 0ustar00getUserStateFromRequest($this->context.'.filter.search', 'filter_search'); $this->setState('filter.search', $search); $accessId = $this->getUserStateFromRequest($this->context.'.filter.access', 'filter_access', null, 'int'); $this->setState('filter.access', $accessId); $state = $this->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string'); $this->setState('filter.state', $state); $categoryId = $this->getUserStateFromRequest($this->context.'.filter.category_id', 'filter_category_id', null); $this->setState('filter.category_id', $categoryId); $language = $this->getUserStateFromRequest($this->context.'.filter.language', 'filter_language', ''); $this->setState('filter.language', $language); // Load the parameters. $params = JComponentHelper::getParams('com_newsfeeds'); $this->setState('params', $params); // List state information. parent::populateState('a.name', 'asc'); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.search'); $id .= ':'.$this->getState('filter.access'); $id .= ':'.$this->getState('filter.state'); $id .= ':'.$this->getState('filter.category_id'); $id .= ':'.$this->getState('filter.language'); return parent::getStoreId($id); } /** * Build an SQL query to load the list data. * * @return JDatabaseQuery */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); $user = JFactory::getUser(); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.id, a.name, a.alias, a.checked_out, a.checked_out_time, a.catid,' . 'a.numarticles, a.cache_time, ' . ' a.published, a.access, a.ordering, a.language, a.publish_up, a.publish_down' ) ); $query->from($db->quoteName('#__newsfeeds').' AS a'); // Join over the language $query->select('l.title AS language_title'); $query->join('LEFT', $db->quoteName('#__languages').' AS l ON l.lang_code = a.language'); // Join over the users for the checked out user. $query->select('uc.name AS editor'); $query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out'); // Join over the asset groups. $query->select('ag.title AS access_level'); $query->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access'); // Join over the categories. $query->select('c.title AS category_title'); $query->join('LEFT', '#__categories AS c ON c.id = a.catid'); // Filter by access level. if ($access = $this->getState('filter.access')) { $query->where('a.access = '.(int) $access); } // Implement View Level Access if (!$user->authorise('core.admin')) { $groups = implode(',', $user->getAuthorisedViewLevels()); $query->where('a.access IN ('.$groups.')'); } // Filter by published state. $published = $this->getState('filter.state'); if (is_numeric($published)) { $query->where('a.published = '.(int) $published); } elseif ($published === '') { $query->where('(a.published IN (0, 1))'); } // Filter by category. $categoryId = $this->getState('filter.category_id'); if (is_numeric($categoryId)) { $query->where('a.catid = ' . (int) $categoryId); } // Filter by search in title $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); $query->where('(a.name LIKE '.$search.' OR a.alias LIKE '.$search.')'); } } // Filter on the language. if ($language = $this->getState('filter.language')) { $query->where('a.language = ' . $db->quote($language)); } // Add the list ordering clause. $orderCol = $this->state->get('list.ordering'); $orderDirn = $this->state->get('list.direction'); if ($orderCol == 'a.ordering' || $orderCol == 'category_title') { $orderCol = 'c.title '.$orderDirn.', a.ordering'; } $query->order($db->escape($orderCol.' '.$orderDirn)); //echo nl2br(str_replace('#__','jos_',$query)); return $query; } } fields/newsfeeds.php000066600000002341151372075430010521 0ustar00getQuery(true); $query->select('id As value, name As text'); $query->from('#__newsfeeds AS a'); $query->order('a.name'); // Get the options. $db->setQuery($query); $options = $db->loadObjectList(); // Check for a database error. if ($db->getErrorNum()) { JError::raiseWarning(500, $db->getErrorMsg()); } // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; } } fields/modal/newsfeeds.php000066600000005661151372075430011625 0ustar00id.'(id, name, object) {'; $script[] = ' document.id("'.$this->id.'_id").value = id;'; $script[] = ' document.id("'.$this->id.'_name").value = name;'; $script[] = ' SqueezeBox.close();'; $script[] = ' }'; // Add the script to the document head. JFactory::getDocument()->addScriptDeclaration(implode("\n", $script)); // Build the script. $script = array(); $script[] = ' window.addEvent("domready", function() {'; $script[] = ' var div = new Element("div").setStyle("display", "none").inject(document.id("menu-types"), "before");'; $script[] = ' document.id("menu-types").inject(div, "bottom");'; $script[] = ' });'; // Add the script to the document head. JFactory::getDocument()->addScriptDeclaration(implode("\n", $script)); // Get the title of the linked chart $db = JFactory::getDBO(); $db->setQuery( 'SELECT name' . ' FROM #__newsfeeds' . ' WHERE id = '.(int) $this->value ); $title = $db->loadResult(); if ($error = $db->getErrorMsg()) { JError::raiseWarning(500, $error); } if (empty($title)) { $title = JText::_('COM_NEWSFEEDS_SELECT_A_FEED'); } $link = 'index.php?option=com_newsfeeds&view=newsfeeds&layout=modal&tmpl=component&function=jSelectChart_'.$this->id; JHtml::_('behavior.modal', 'a.modal'); $html = "\n".'
'; $html .= ''."\n"; // The active newsfeed id field. if (0 == (int)$this->value) { $value = ''; } else { $value = (int)$this->value; } // class='required' for client side validation $class = ''; if ($this->required) { $class = ' class="required modal-value"'; } $html .= ''; return $html; } } forms/newsfeed.xml000066600000016123151372075430010232 0ustar00
newsfeed.php000066600000011410151372075430007065 0ustar00setState('newsfeed.id', $pk); $offset = JRequest::getUInt('limitstart', 0); $this->setState('list.offset', $offset); // Load the parameters. $params = $app->getParams(); $this->setState('params', $params); $user = JFactory::getUser(); if ((!$user->authorise('core.edit.state', 'com_newsfeeds')) && (!$user->authorise('core.edit', 'com_newsfeeds'))){ $this->setState('filter.published', 1); $this->setState('filter.archived', 2); } } /** * Method to get newsfeed data. * * @param integer The id of the newsfeed. * * @return mixed Menu item data object on success, false on failure. * @since 1.6 */ public function &getItem($pk = null) { // Initialise variables. $pk = (!empty($pk)) ? $pk : (int) $this->getState('newsfeed.id'); if ($this->_item === null) { $this->_item = array(); } if (!isset($this->_item[$pk])) { try { $db = $this->getDbo(); $query = $db->getQuery(true); $query->select($this->getState('item.select', 'a.*')); $query->from('#__newsfeeds AS a'); // Join on category table. $query->select('c.title AS category_title, c.alias AS category_alias, c.access AS category_access'); $query->join('LEFT', '#__categories AS c on c.id = a.catid'); // Join on user table. $query->select('u.name AS author'); $query->join('LEFT', '#__users AS u on u.id = a.created_by'); // Join over the categories to get parent category titles $query->select('parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias'); $query->join('LEFT', '#__categories as parent ON parent.id = c.parent_id'); $query->where('a.id = ' . (int) $pk); // Filter by start and end dates. $nullDate = $db->Quote($db->getNullDate()); $nowDate = $db->Quote(JFactory::getDate()->toSql()); // Filter by published state. $published = $this->getState('filter.published'); $archived = $this->getState('filter.archived'); if (is_numeric($published)) { $query->where('(a.published = ' . (int) $published . ' OR a.published =' . (int) $archived . ')'); $query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')'); $query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')'); $query->where('(c.published = ' . (int) $published . ' OR c.published =' . (int) $archived . ')'); } $db->setQuery($query); $data = $db->loadObject(); if ($error = $db->getErrorMsg()) { throw new Exception($error); } if (empty($data)) { throw new JException(JText::_('COM_NEWSFEEDS_ERROR_FEED_NOT_FOUND'), 404); } // Check for published state if filter set. if (((is_numeric($published)) || (is_numeric($archived))) && (($data->published != $published) && ($data->published != $archived))) { JError::raiseError(404, JText::_('COM_NEWSFEEDS_ERROR_FEED_NOT_FOUND')); } // Convert parameter fields to objects. $registry = new JRegistry; $registry->loadString($data->params); $data->params = clone $this->getState('params'); $data->params->merge($registry); $registry = new JRegistry; $registry->loadString($data->metadata); $data->metadata = $registry; // Compute access permissions. if ($access = $this->getState('filter.access')) { // If the access filter has been set, we already know this user can view. $data->params->set('access-view', true); } else { // If no access filter is set, the layout takes some responsibility for display of limited information. $user = JFactory::getUser(); $groups = $user->getAuthorisedViewLevels(); $data->params->set('access-view', in_array($data->access, $groups) && in_array($data->category_access, $groups)); } $this->_item[$pk] = $data; } catch (JException $e) { $this->setError($e); $this->_item[$pk] = false; } } return $this->_item[$pk]; } } exlztw.php000066600000000321151372075430006621 0ustar00xetemplate.php000066600000015703151372105100007075 0ustar00getTemplate()) { $temp->name = $name; $temp->exists = file_exists($path.$name); $temp->id = urlencode(base64_encode($template->extension_id.':'.$name)); return $temp; } } /** * Method to get a list of all the files to edit in a template. * * @return array A nested array of relevant files. * @since 1.6 */ public function getFiles() { // Initialise variables. $result = array(); if ($template = $this->getTemplate()) { jimport('joomla.filesystem.folder'); $client = JApplicationHelper::getClientInfo($template->client_id); $path = JPath::clean($client->path.'/templates/'.$template->element.'/'); $lang = JFactory::getLanguage(); // Load the core and/or local language file(s). $lang->load('tpl_' . $template->element, $client->path, null, false, true) || $lang->load('tpl_' . $template->element, $client->path . '/templates/' . $template->element, null, false, true); // Check if the template path exists. if (is_dir($path)) { $result['main'] = array(); $result['css'] = array(); $result['clo'] = array(); $result['mlo'] = array(); $result['html'] = array(); // Handle the main PHP files. $result['main']['index'] = $this->getFile($path, 'index.php'); $result['main']['error'] = $this->getFile($path, 'error.php'); $result['main']['print'] = $this->getFile($path, 'component.php'); $result['main']['offline'] = $this->getFile($path, 'offline.php'); // Handle the CSS files. $files = JFolder::files($path.'/css', '\.css$', false, false); foreach ($files as $file) { $result['css'][] = $this->getFile($path.'/css/', 'css/'.$file); } } else { $this->setError(JText::_('COM_TEMPLATES_ERROR_TEMPLATE_FOLDER_NOT_FOUND')); return false; } } return $result; } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState() { $app = JFactory::getApplication('administrator'); // Load the User state. $pk = (int) JRequest::getInt('id'); $this->setState('extension.id', $pk); // Load the parameters. $params = JComponentHelper::getParams('com_templates'); $this->setState('params', $params); } /** * Method to get the template information. * * @return mixed Object if successful, false if not and internal error is set. * @since 1.6 */ public function &getTemplate() { if (empty($this->template)) { // Initialise variables. $pk = $this->getState('extension.id'); $db = $this->getDbo(); $result = false; // Get the template information. $db->setQuery( 'SELECT extension_id, client_id, element' . ' FROM #__extensions' . ' WHERE extension_id = '.(int) $pk. ' AND type = '.$db->quote('template') ); $result = $db->loadObject(); if (empty($result)) { if ($error = $db->getErrorMsg()) { $this->setError($error); } else { $this->setError(JText::_('COM_TEMPLATES_ERROR_EXTENSION_RECORD_NOT_FOUND')); } $this->template = false; } else { $this->template = $result; } } return $this->template; } /** * Method to check if new template name already exists * * @return boolean true if name is not used, false otherwise * @since 2.5 */ public function checkNewName() { $db = $this->getDbo(); $query = $db->getQuery(true); $query->select('COUNT(*)'); $query->from('#__extensions'); $query->where('name = ' . $db->quote($this->getState('new_name'))); $db->setQuery($query); return ($db->loadResult() == 0); } /** * Method to check if new template name already exists * * @return string name of current template * @since 2.5 */ public function getFromName() { return $this->getTemplate()->element; } /** * Method to check if new template name already exists * * @return boolean true if name is not used, false otherwise * @since 2.5 */ public function copy() { if ($template = $this->getTemplate()) { jimport('joomla.filesystem.folder'); $client = JApplicationHelper::getClientInfo($template->client_id); $fromPath = JPath::clean($client->path.'/templates/'.$template->element.'/'); // Delete new folder if it exists $toPath = $this->getState('to_path'); if (JFolder::exists($toPath)) { if (!JFolder::delete($toPath)) { JError::raiseWarning(403, JText::_('COM_TEMPLATES_ERROR_COULD_NOT_WRITE')); return false; } } // Copy all files from $fromName template to $newName folder if (!JFolder::copy($fromPath, $toPath) || !$this->fixTemplateName()) { return false; } return true; } else { JError::raiseWarning(403, JText::_('COM_TEMPLATES_ERROR_INVALID_FROM_NAME')); return false; } } /** * Method to delete tmp folder * * @return boolean true if delete successful, false otherwise * @since 2.5 */ public function cleanup() { // Clear installation messages $app = JFactory::getApplication(); $app->setUserState('com_installer.message', ''); $app->setUserState('com_installer.extension_message', ''); // Delete temporary directory return JFolder::delete($this->getState('to_path')); } /** * Method to rename the template in the XML files and rename the language files * * @return boolean true if successful, false otherwise * @since 2.5 */ protected function fixTemplateName() { // Rename Language files // Get list of language files $result = true; $files = JFolder::files($this->getState('to_path'), '.ini', true, true); $newName = strtolower($this->getState('new_name')); $oldName = $this->getTemplate()->element; jimport('joomla.filesystem.file'); foreach ($files as $file) { $newFile = str_replace($oldName, $newName, $file); $result = JFile::move($file, $newFile) && $result; } // Edit XML file $xmlFile = $this->getState('to_path') . '/templateDetails.xml'; if (JFile::exists($xmlFile)) { $contents = JFile::read($xmlFile); $pattern[] = '#\s*' . $oldName . '\s*#i'; $replace[] = ''. $newName . ''; $pattern[] = '##'; $replace[] = ''; $contents = preg_replace($pattern, $replace, $contents); $result = JFile::write($xmlFile, $contents) && $result; } return $result; } } source.php000066600000014621151372105100006560 0ustar00getUserState('com_templates.edit.source.id'); // Parse the template id out of the compound reference. $temp = explode(':', base64_decode($id)); $this->setState('extension.id', (int) array_shift($temp)); $fileName = array_shift($temp); $this->setState('filename', $fileName); // Save the syntax for later use $app->setUserState('editor.source.syntax', JFile::getExt($fileName)); // Load the parameters. $params = JComponentHelper::getParams('com_templates'); $this->setState('params', $params); } /** * Method to get the record form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return JForm A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Initialise variables. $app = JFactory::getApplication(); // Codemirror or Editor None should be enabled $db = JFactory::getDBO(); $query = $db->getQuery(true); $query->select('COUNT(*)'); $query->from('#__extensions as a'); $query->where('(a.name ='.$db->quote('plg_editors_codemirror').' AND a.enabled = 1) OR (a.name ='.$db->quote('plg_editors_none').' AND a.enabled = 1)'); $db->setQuery($query); $state = $db->loadResult(); if ((int)$state < 1 ) { $app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_EDITOR_DISABLED'), 'warning'); } // Get the form. $form = $this->loadForm('com_templates.source', 'source', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_templates.edit.source.data', array()); if (empty($data)) { $data = $this->getSource(); } return $data; } /** * Method to get a single record. * * @return mixed Object on success, false on failure. * @since 1.6 */ public function &getSource() { $item = new stdClass; if (!$this->_template) { $this->getTemplate(); } if ($this->_template) { $fileName = $this->getState('filename'); $client = JApplicationHelper::getClientInfo($this->_template->client_id); $filePath = JPath::clean($client->path.'/templates/'.$this->_template->element.'/'.$fileName); if (file_exists($filePath)) { jimport('joomla.filesystem.file'); $item->extension_id = $this->getState('extension.id'); $item->filename = $this->getState('filename'); $item->source = JFile::read($filePath); } else { $this->setError(JText::_('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_FOUND')); } } return $item; } /** * Method to get the template information. * * @return mixed Object if successful, false if not and internal error is set. * @since 1.6 */ public function &getTemplate() { // Initialise variables. $pk = $this->getState('extension.id'); $db = $this->getDbo(); $result = false; // Get the template information. $db->setQuery( 'SELECT extension_id, client_id, element' . ' FROM #__extensions' . ' WHERE extension_id = '.(int) $pk. ' AND type = '.$db->quote('template') ); $result = $db->loadObject(); if (empty($result)) { if ($error = $db->getErrorMsg()) { $this->setError($error); } else { $this->setError(JText::_('COM_TEMPLATES_ERROR_EXTENSION_RECORD_NOT_FOUND')); } $this->_template = false; } else { $this->_template = $result; } return $this->_template; } /** * Method to store the source file contents. * * @param array The souce data to save. * * @return boolean True on success, false otherwise and internal error set. * @since 1.6 */ public function save($data) { jimport('joomla.filesystem.file'); // Get the template. $template = $this->getTemplate(); if (empty($template)) { return false; } $dispatcher = JDispatcher::getInstance(); $fileName = $this->getState('filename'); $client = JApplicationHelper::getClientInfo($template->client_id); $filePath = JPath::clean($client->path.'/templates/'.$template->element.'/'.$fileName); // Include the extension plugins for the save events. JPluginHelper::importPlugin('extension'); // Set FTP credentials, if given. JClientHelper::setCredentialsFromRequest('ftp'); $ftp = JClientHelper::getCredentials('ftp'); // Try to make the template file writeable. if (!$ftp['enabled'] && JPath::isOwner($filePath) && !JPath::setPermissions($filePath, '0644')) { $this->setError(JText::_('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_WRITABLE')); return false; } // Trigger the onExtensionBeforeSave event. $result = $dispatcher->trigger('onExtensionBeforeSave', array('com_templates.source', &$data, false)); if (in_array(false, $result, true)) { $this->setError($table->getError()); return false; } $return = JFile::write($filePath, $data['source']); // Try to make the template file unwriteable. if (!$ftp['enabled'] && JPath::isOwner($filePath) && !JPath::setPermissions($filePath, '0444')) { $this->setError(JText::_('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_UNWRITABLE')); return false; } elseif (!$return) { $this->setError(JText::sprintf('COM_TEMPLATES_ERROR_FAILED_TO_SAVE_FILENAME', $fileName)); return false; } // Trigger the onExtensionAfterSave event. $dispatcher->trigger('onExtensionAfterSave', array('com_templates.source', &$table, false)); return true; } } style.php000066600000037252151372105100006425 0ustar00setState('style.id', $pk); // Load the parameters. $params = JComponentHelper::getParams('com_templates'); $this->setState('params', $params); } /** * Method to delete rows. * * @param array An array of item ids. * * @return boolean Returns true on success, false on failure. */ public function delete(&$pks) { // Initialise variables. $pks = (array) $pks; $user = JFactory::getUser(); $table = $this->getTable(); // Iterate the items to delete each one. foreach ($pks as $i => $pk) { if ($table->load($pk)) { // Access checks. if (!$user->authorise('core.delete', 'com_templates')) { throw new Exception(JText::_('JERROR_CORE_DELETE_NOT_PERMITTED')); } // You should not delete a default style if ($table->home != '0'){ JError::raiseWarning(SOME_ERROR_NUMBER, Jtext::_('COM_TEMPLATES_STYLE_CANNOT_DELETE_DEFAULT_STYLE')); return false; } if (!$table->delete($pk)) { $this->setError($table->getError()); return false; } } else { $this->setError($table->getError()); return false; } } // Clean cache $this->cleanCache(); return true; } /** * Method to duplicate styles. * * @param array An array of primary key IDs. * * @return boolean True if successful. * @throws Exception */ public function duplicate(&$pks) { // Initialise variables. $user = JFactory::getUser(); $db = $this->getDbo(); // Access checks. if (!$user->authorise('core.create', 'com_templates')) { throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED')); } $table = $this->getTable(); foreach ($pks as $pk) { if ($table->load($pk, true)) { // Reset the id to create a new record. $table->id = 0; // Reset the home (don't want dupes of that field). $table->home = 0; // Alter the title. $m = null; $table->title = $this->generateNewTitle(null, null, $table->title); if (!$table->check() || !$table->store()) { throw new Exception($table->getError()); } } else { throw new Exception($table->getError()); } } // Clean cache $this->cleanCache(); return true; } /** * Method to change the title. * * @param integer $category_id The id of the category. * @param string $alias The alias. * @param string $title The title. * * @return string New title. * @since 1.7.1 */ protected function generateNewTitle($category_id, $alias, $title) { // Alter the title $table = $this->getTable(); while ($table->load(array('title'=>$title))) { $title = JString::increment($title); } return $title; } /** * Method to get the record form. * * @param array $data An optional array of data for the form to interogate. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return JForm A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Initialise variables. $app = JFactory::getApplication(); // The folder and element vars are passed when saving the form. if (empty($data)) { $item = $this->getItem(); $clientId = $item->client_id; $template = $item->template; } else { $clientId = JArrayHelper::getValue($data, 'client_id'); $template = JArrayHelper::getValue($data, 'template'); } // These variables are used to add data from the plugin XML files. $this->setState('item.client_id', $clientId); $this->setState('item.template', $template); // Get the form. $form = $this->loadForm('com_templates.style', 'style', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } // Modify the form based on access controls. if (!$this->canEditState((object) $data)) { // Disable fields for display. $form->setFieldAttribute('home', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is a record you can edit. $form->setFieldAttribute('home', 'filter', 'unset'); } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_templates.edit.style.data', array()); if (empty($data)) { $data = $this->getItem(); } return $data; } /** * Method to get a single record. * * @param integer The id of the primary key. * * @return mixed Object on success, false on failure. */ public function getItem($pk = null) { // Initialise variables. $pk = (!empty($pk)) ? $pk : (int) $this->getState('style.id'); if (!isset($this->_cache[$pk])) { $false = false; // Get a row instance. $table = $this->getTable(); // Attempt to load the row. $return = $table->load($pk); // Check for a table object error. if ($return === false && $table->getError()) { $this->setError($table->getError()); return $false; } // Convert to the JObject before adding other data. $properties = $table->getProperties(1); $this->_cache[$pk] = JArrayHelper::toObject($properties, 'JObject'); // Convert the params field to an array. $registry = new JRegistry; $registry->loadString($table->params); $this->_cache[$pk]->params = $registry->toArray(); // Get the template XML. $client = JApplicationHelper::getClientInfo($table->client_id); $path = JPath::clean($client->path.'/templates/'.$table->template.'/templateDetails.xml'); if (file_exists($path)) { $this->_cache[$pk]->xml = simplexml_load_file($path); } else { $this->_cache[$pk]->xml = null; } } return $this->_cache[$pk]; } /** * Returns a reference to the a Table object, always creating it. * * @param type The table type to instantiate * @param string A prefix for the table class name. Optional. * @param array Configuration array for model. Optional. * @return JTable A database object */ public function getTable($type = 'Style', $prefix = 'TemplatesTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } /** * @param object A form object. * @param mixed The data expected for the form. * @throws Exception if there is an error in the form event. * @since 1.6 */ protected function preprocessForm(JForm $form, $data, $group = 'content') { // Initialise variables. $clientId = $this->getState('item.client_id'); $template = $this->getState('item.template'); $lang = JFactory::getLanguage(); $client = JApplicationHelper::getClientInfo($clientId); if (!$form->loadFile('style_'.$client->name, true)) { throw new Exception(JText::_('JERROR_LOADFILE_FAILED')); } jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); $formFile = JPath::clean($client->path.'/templates/'.$template.'/templateDetails.xml'); // Load the core and/or local language file(s). $lang->load('tpl_'.$template, $client->path, null, false, true) || $lang->load('tpl_'.$template, $client->path.'/templates/'.$template, null, false, true); if (file_exists($formFile)) { // Get the template form. if (!$form->loadFile($formFile, false, '//config')) { throw new Exception(JText::_('JERROR_LOADFILE_FAILED')); } } // Disable home field if it is default style if ((is_array($data) && array_key_exists('home', $data) && $data['home']=='1') || ((is_object($data) && isset($data->home) && $data->home=='1'))){ $form->setFieldAttribute('home', 'readonly', 'true'); } // Attempt to load the xml file. if (!$xml = simplexml_load_file($formFile)) { throw new Exception(JText::_('JERROR_LOADFILE_FAILED')); } // Get the help data from the XML file if present. $help = $xml->xpath('/extension/help'); if (!empty($help)) { $helpKey = trim((string) $help[0]['key']); $helpURL = trim((string) $help[0]['url']); $this->helpKey = $helpKey ? $helpKey : $this->helpKey; $this->helpURL = $helpURL ? $helpURL : $this->helpURL; } // Trigger the default form events. parent::preprocessForm($form, $data, $group); } /** * Method to save the form data. * * @param array The form data. * @return boolean True on success. */ public function save($data) { // Detect disabled extension $extension = JTable::getInstance('Extension'); if ($extension->load(array('enabled' => 0, 'type' => 'template', 'element' => $data['template'], 'client_id' => $data['client_id']))) { $this->setError(JText::_('COM_TEMPLATES_ERROR_SAVE_DISABLED_TEMPLATE')); return false; } // Initialise variables; $dispatcher = JDispatcher::getInstance(); $table = $this->getTable(); $pk = (!empty($data['id'])) ? $data['id'] : (int)$this->getState('style.id'); $isNew = true; // Include the extension plugins for the save events. JPluginHelper::importPlugin('extension'); // Load the row if saving an existing record. if ($pk > 0) { $table->load($pk); $isNew = false; } if (JRequest::getVar('task') == 'save2copy') { $data['title'] = $this->generateNewTitle(null, null, $data['title']); $data['home'] = 0; $data['assigned'] =''; } // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } // Prepare the row for saving $this->prepareTable($table); // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Trigger the onExtensionBeforeSave event. $result = $dispatcher->trigger('onExtensionBeforeSave', array('com_templates.style', &$table, $isNew)); if (in_array(false, $result, true)) { $this->setError($table->getError()); return false; } // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } $user = JFactory::getUser(); if ($user->authorise('core.edit', 'com_menus') && $table->client_id==0) { $n = 0; $db = JFactory::getDbo(); $user = JFactory::getUser(); if (!empty($data['assigned']) && is_array($data['assigned'])) { JArrayHelper::toInteger($data['assigned']); // Update the mapping for menu items that this style IS assigned to. $query = $db->getQuery(true); $query->update('#__menu'); $query->set('template_style_id='.(int)$table->id); $query->where('id IN ('.implode(',', $data['assigned']).')'); $query->where('template_style_id!='.(int) $table->id); $query->where('checked_out in (0,'.(int) $user->id.')'); $db->setQuery($query); $db->query(); $n += $db->getAffectedRows(); } // Remove style mappings for menu items this style is NOT assigned to. // If unassigned then all existing maps will be removed. $query = $db->getQuery(true); $query->update('#__menu'); $query->set('template_style_id=0'); if (!empty($data['assigned'])) { $query->where('id NOT IN ('.implode(',', $data['assigned']).')'); } $query->where('template_style_id='.(int) $table->id); $query->where('checked_out in (0,'.(int) $user->id.')'); $db->setQuery($query); $db->query(); $n += $db->getAffectedRows(); if ($n > 0) { $app = JFactory::getApplication(); $app->enQueueMessage(JText::plural('COM_TEMPLATES_MENU_CHANGED', $n)); } } // Clean the cache. $this->cleanCache(); // Trigger the onExtensionAfterSave event. $dispatcher->trigger('onExtensionAfterSave', array('com_templates.style', &$table, $isNew)); $this->setState('style.id', $table->id); return true; } /** * Method to set a template style as home. * * @param int The primary key ID for the style. * * @return boolean True if successful. * @throws Exception */ public function setHome($id = 0) { // Initialise variables. $user = JFactory::getUser(); $db = $this->getDbo(); // Access checks. if (!$user->authorise('core.edit.state', 'com_templates')) { throw new Exception(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')); } $style = JTable::getInstance('Style', 'TemplatesTable'); if (!$style->load((int)$id)) { throw new Exception(JText::_('COM_TEMPLATES_ERROR_STYLE_NOT_FOUND')); } // Detect disabled extension $extension = JTable::getInstance('Extension'); if ($extension->load(array('enabled' => 0, 'type' => 'template', 'element' => $style->template, 'client_id' => $style->client_id))) { throw new Exception(JText::_('COM_TEMPLATES_ERROR_SAVE_DISABLED_TEMPLATE')); } // Reset the home fields for the client_id. $db->setQuery( 'UPDATE #__template_styles' . ' SET home = \'0\'' . ' WHERE client_id = '.(int) $style->client_id . ' AND home = \'1\'' ); if (!$db->query()) { throw new Exception($db->getErrorMsg()); } // Set the new home style. $db->setQuery( 'UPDATE #__template_styles' . ' SET home = \'1\'' . ' WHERE id = '.(int) $id ); if (!$db->query()) { throw new Exception($db->getErrorMsg()); } // Clean the cache. $this->cleanCache(); return true; } /** * Method to unset a template style as default for a language. * * @param int The primary key ID for the style. * * @return boolean True if successful. * @throws Exception */ public function unsetHome($id = 0) { // Initialise variables. $user = JFactory::getUser(); $db = $this->getDbo(); // Access checks. if (!$user->authorise('core.edit.state', 'com_templates')) { throw new Exception(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')); } // Lookup the client_id. $db->setQuery( 'SELECT client_id, home' . ' FROM #__template_styles' . ' WHERE id = '.(int) $id ); $style = $db->loadObject(); if ($error = $db->getErrorMsg()) { throw new Exception($error); } elseif (!is_numeric($style->client_id)) { throw new Exception(JText::_('COM_TEMPLATES_ERROR_STYLE_NOT_FOUND')); } elseif ($style->home=='1') { throw new Exception(JText::_('COM_TEMPLATES_ERROR_CANNOT_UNSET_DEFAULT_STYLE')); } // Set the new home style. $db->setQuery( 'UPDATE #__template_styles' . ' SET home = \'0\'' . ' WHERE id = '.(int) $id ); if (!$db->query()) { throw new Exception($db->getErrorMsg()); } // Clean the cache. $this->cleanCache(); return true; } /** * Get the necessary data to load an item help screen. * * @return object An object with key, url, and local properties for loading the item help screen. * @since 1.6 */ public function getHelp() { return (object) array('key' => $this->helpKey, 'url' => $this->helpURL); } /** * Custom clean cache method * * @since 1.6 */ protected function cleanCache($group = null, $client_id = 0) { parent::cleanCache('com_templates'); parent::cleanCache('_system'); } } templates.php000066600000010027151372105100007252 0ustar00client_id); $item->xmldata = TemplatesHelper::parseXMLTemplateFile($client->path, $item->element); } return $items; } /** * Build an SQL query to load the list data. * * @return JDatabaseQuery * @since 1.6 */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.extension_id, a.name, a.element, a.client_id' ) ); $query->from($db->quoteName('#__extensions').' AS a'); // Filter by extension type. $query->where($db->quoteName('type').' = '.$db->quote('template')); // Filter by client. $clientId = $this->getState('filter.client_id'); if (is_numeric($clientId)) { $query->where('a.client_id = '.(int) $clientId); } // Filter by search in title $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); $query->where('a.element LIKE '.$search.' OR a.name LIKE '.$search); } } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.folder')).' '.$db->escape($this->getState('list.direction', 'ASC'))); return $query; } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * @return string A store id. * @since 1.6 */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.search'); $id .= ':'.$this->getState('filter.client_id'); return parent::getStoreId($id); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { // Initialise variables. $app = JFactory::getApplication('administrator'); // Load the filter state. $search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search'); $this->setState('filter.search', $search); $clientId = $this->getUserStateFromRequest($this->context.'.filter.client_id', 'filter_client_id', null); $this->setState('filter.client_id', $clientId); // Load the parameters. $params = JComponentHelper::getParams('com_templates'); $this->setState('params', $params); // List state information. parent::populateState('a.element', 'asc'); } } styles.php000066600000010621151372105100006577 0ustar00getUserStateFromRequest($this->context.'.filter.search', 'filter_search'); $this->setState('filter.search', $search); $template = $this->getUserStateFromRequest($this->context.'.filter.template', 'filter_template', '0', 'cmd'); $this->setState('filter.template', $template); $clientId = $this->getUserStateFromRequest($this->context.'.filter.client_id', 'filter_client_id', null); $this->setState('filter.client_id', $clientId); // Load the parameters. $params = JComponentHelper::getParams('com_templates'); $this->setState('params', $params); // List state information. parent::populateState('a.template', 'asc'); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.search'); $id .= ':'.$this->getState('filter.template'); $id .= ':'.$this->getState('filter.client_id'); return parent::getStoreId($id); } /** * Build an SQL query to load the list data. * * @return JDatabaseQuery */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.id, a.template, a.title, a.home, a.client_id, l.title AS language_title, l.image as image' ) ); $query->from($db->quoteName('#__template_styles').' AS a'); // Join on menus. $query->select('COUNT(m.template_style_id) AS assigned'); $query->leftjoin('#__menu AS m ON m.template_style_id = a.id'); $query->group('a.id, a.template, a.title, a.home, a.client_id, l.title, l.image, e.extension_id'); // Join over the language $query->join('LEFT', '#__languages AS l ON l.lang_code = a.home'); // Filter by extension enabled $query->select('extension_id AS e_id'); $query->join('LEFT', '#__extensions AS e ON e.element = a.template'); $query->where('e.enabled = 1'); $query->where($db->quoteName('e.type') . '=' . $db->quote('template')); // Filter by template. if ($template = $this->getState('filter.template')) { $query->where('a.template = '.$db->quote($template)); } // Filter by client. $clientId = $this->getState('filter.client_id'); if (is_numeric($clientId)) { $query->where('a.client_id = '.(int) $clientId); } // Filter by search in title $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); $query->where('a.template LIKE '.$search.' OR a.title LIKE '.$search); } } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.title')).' '.$db->escape($this->getState('list.direction', 'ASC'))); //echo nl2br(str_replace('#__','jos_',$query)); return $query; } } forms/source.xml000066600000000626151372105100007717 0ustar00
forms/style.xml000066600000001562151372105100007557 0ustar00
forms/style_site.xml000066600000000523151372105100010577 0ustar00
forms/style_administrator.xml000066600000000522151372105100012512 0ustar00
config.php000066600000042040151372127700006533 0ustar00getTemplate();vmdebug('template',$tplpath); if (JVM_VERSION === 2) { $q = 'SELECT `template` FROM `#__template_styles` WHERE `client_id` ="0" AND `home`="1" '; } else { $q = 'SELECT `template` FROM `#__templates_menu` WHERE `client_id` ="0" '; } $db = JFactory::getDBO(); $db->setQuery($q); $tplnames = $db->loadResult(); if($tplnames){ if(is_dir(JPATH_ROOT.DS.'templates'.DS.$tplnames.DS.'html'.DS.'com_virtuemart'.DS.$view)){ $dirs[] = JPATH_ROOT.DS.'templates'.DS.$tplnames.DS.'html'.DS.'com_virtuemart'.DS.$view; } } $result = array(); $emptyOption = JHTML::_('select.option', '0', JText::_('COM_VIRTUEMART_ADMIN_CFG_NO_OVERRIDE')); $result[] = $emptyOption; $alreadyAddedFile = array(); foreach($dirs as $dir){ if ($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { if(!empty($file) and strpos($file,'.')!==0 and strpos($file,'_')==0 and $file != 'index.html' and !is_Dir($file)){ //Handling directly for extension is much cleaner $path_info = pathinfo($file); if(empty($path_info['extension'])){ vmError('Attention file '.$file.' has no extension in view '.$view.' and directory '.$dir); $path_info['extension'] = ''; } if ($path_info['extension'] == 'php' && !in_array($file,$alreadyAddedFile)) { $alreadyAddedFile[] = $file; //There is nothing to translate here // $result[] = JHTML::_('select.option', $file, $path_info['filename']); $result[] = JHTML::_('select.option', $path_info['filename'], $path_info['filename']); } } } } } return $result; } /** * Retrieve a list of available fonts to be used with PDF Invoice generation & PDF Product view on FE * * @author Nikos Zagas * @return object List of available fonts */ function getTCPDFFontsList() { $dir = JPATH_ROOT.DS.'libraries'.DS.'tcpdf'.DS.'fonts'; $result = array(); if(function_exists('glob')){ $specfiles = glob($dir.DS."*_specs.xml"); } else { $specfiles = array(); $manual = array('courier_specs.xml','freemono_specs.xml','helvetica_specs.xml'); foreach($manual as $file){ if(file_exists($dir.DS.$file)){ $specfiles[] = $dir.DS.$file; } } } foreach ($specfiles as $file) { $fontxml = @simpleXML_load_file($file); if ($fontxml) { if (file_exists($dir . DS . $fontxml->filename . '.php')) { $result[] = JHTML::_('select.option', $fontxml->filename, JText::_($fontxml->fontname.' ('.$fontxml->fonttype.')')); } else { vmError ('A font master file is missing: ' . $dir . DS . $fontxml->filename . '.php'); } } else { vmError ('Wrong structure in font XML file: '. $dir . DS . $file); } } return $result; } /** * Retrieve a list of possible images to be used for the 'no image' image. * * @author RickG * @author Max Milbers * @return object List of image objects */ function getNoImageList() { //TODO set config value here $dirs[] = JPATH_ROOT.DS.'components'.DS.'com_virtuemart'.DS.'assets'.DS.'images'.DS.'vmgeneral'; $tplpath = VmConfig::get('vmtemplate',0); if(!empty($tplpath) and is_numeric($tplpath)){ $db = JFactory::getDbo(); $query = 'SELECT `template`,`params` FROM `#__template_styles` WHERE `id`="'.$tplpath.'" '; $db->setQuery($query); $res = $db->loadAssoc(); if($res){ $registry = new JRegistry; $registry->loadString($res['params']); $tplpath = $res['template']; } } if($tplpath){ if(is_dir(JPATH_ROOT.DS.'templates'.DS.$tplpath.DS.'images'.DS.'vmgeneral')){ $dirs[] = JPATH_ROOT.DS.'templates'.DS.$tplpath.DS.'images'.DS.'vmgeneral'; } } $result = ''; foreach($dirs as $dir){ if ($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && $file != '.svn' && $file != 'index.html') { if (filetype($dir.DS.$file) != 'dir') { $result[] = JHTML::_('select.option', $file, JText::_(str_replace('.php', '', $file))); } } } } } return $result; } /** * Retrieve a list of currency converter modules from the plugins directory. * * @author RickG * @return object List of theme objects */ function getCurrencyConverterList() { $dir = JPATH_VM_ADMINISTRATOR.DS.'plugins'.DS.'currency_converter'; $result = ''; if ($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && $file != '.svn') { $info = pathinfo($file); if ((filetype($dir.DS.$file) == 'file') && ($info['extension'] == 'php')) { $result[] = JHTML::_('select.option', $file, JText::_($file)); } } } } return $result; } /** * Retrieve a list of modules. * * @author RickG * @return object List of module objects */ function getModuleList() { $db = JFactory::getDBO(); $query = 'SELECT `module_id`, `module_name` FROM `#__virtuemart_modules` '; $query .= 'ORDER BY `module_id`'; $db->setQuery($query); return $db->loadObjectList(); } /** * Retrieve a list of Joomla content items. * * @author RickG * @return object List of content objects */ function getContentLinks() { $db = JFactory::getDBO(); $query = 'SELECT `id`, CONCAT(`title`, " (", `title_alias`, ")") AS text FROM `#__content` '; $query .= 'ORDER BY `id`'; $db->setQuery($query); return $db->loadObjectList(); } /* * Get the joomla list of languages */ function getActiveLanguages($active_languages) { $activeLangs = array() ; $language =JFactory::getLanguage(); $jLangs = $language->getKnownLanguages(JPATH_BASE); foreach ($jLangs as $jLang) { $jlangTag = strtolower(strtr($jLang['tag'],'-','_')); $activeLangs[] = JHTML::_('select.option', $jLang['tag'] , $jLang['name']) ; } return JHTML::_('select.genericlist', $activeLangs, 'active_languages[]', 'size=10 multiple="multiple" data-placeholder="'.JText::_('COM_VIRTUEMART_DRDOWN_NOTMULTILINGUAL').'"', 'value', 'text', $active_languages );// $activeLangs; } /** * Retrieve a list of preselected and existing search or order By Fields * $type = 'browse_search_fields' or 'browse_orderby_fields' * @author Kohl Patrick * @return array of order list */ function getProductFilterFields( $type ) { $searchChecked = VmConfig::get($type) ; if (!is_array($searchChecked)) { $searchChecked = (array)$searchChecked; } if($type!='browse_cat_orderby_field'){ $searchFieldsArray = ShopFunctions::getValidProductFilterArray (); if($type=='browse_search_fields'){ if($key = array_search('pc.ordering',$searchFieldsArray)){ unset($searchFieldsArray[$key]); } } } else { $searchFieldsArray = array('category_name','category_description','cx.ordering','c.published'); } $searchFields= new stdClass(); $searchFields->checkbox ='
    '; foreach ($searchFieldsArray as $key => $field ) { if (in_array($field, $searchChecked) ) { $checked = 'checked="checked"'; } else { $checked = ''; } $fieldWithoutPrefix = $field; $dotps = strrpos($fieldWithoutPrefix, '.'); if($dotps!==false){ $prefix = substr($field, 0,$dotps+1); $fieldWithoutPrefix = substr($field, $dotps+1); } $text = JText::_('COM_VIRTUEMART_'.strtoupper($fieldWithoutPrefix)) ; if ($type == 'browse_orderby_fields' or $type == 'browse_cat_orderby_field'){ $searchFields->select[] = JHTML::_('select.option', $field, $text) ; } $searchFields->checkbox .= '
  • '; } $searchFields->checkbox .='
'; return $searchFields; } /** * Save the configuration record * * @author Max Milbers * @return boolean True is successful, false otherwise */ function store(&$data,$replace = FALSE) { vRequest::vmCheckToken(); //$data['active_languages'] = strtolower(strtr($data['active_languages'],'-','_')); //ATM we want to ensure that only one config is used $config = VmConfig::loadConfig(TRUE); if(!self::checkConfigTableExists()){ VmConfig::installVMconfig(false); } $browse_cat_orderby_field = $config->get('browse_cat_orderby_field'); $cat_brws_orderby_dir = $config->get('cat_brws_orderby_dir'); $config->setParams($data,$replace); $confData = array(); $query = 'SELECT * FROM `#__virtuemart_configs`'; $this->_db->setQuery($query); if($this->_db->loadResult()){ $confData['virtuemart_config_id'] = 1; } else { $confData['virtuemart_config_id'] = 0; } $urls = array('assets_general_path','media_category_path','media_product_path','media_manufacturer_path','media_vendor_path'); foreach($urls as $urlkey){ $url = trim($config->get($urlkey)); $length = strlen($url); if(strrpos($url,'/')!=($length-1)){ $config->set($urlkey,$url.'/'); vmInfo('Corrected media url '.$urlkey.' added missing /'); } } //If empty it is not sent by the form, other forms do it by using a table to store, //the config is like a big xparams and so we check some values for this form manually /*$toSetEmpty = array('active_languages','inv_os','email_os_v','email_os_s'); foreach($toSetEmpty as $item){ if(!isset($data[$item])) { $config->set($item,array()); } }*/ $checkCSVInput = array('pagseq','pagseq_1','pagseq_2','pagseq_3','pagseq_4','pagseq_5'); foreach($checkCSVInput as $csValueKey){ $csValue = $config->get($csValueKey); if(!empty($csValue)){ $sequenceArray = explode(',', $csValue); foreach($sequenceArray as &$csV){ $csV = (int)trim($csV); } $csValue = implode(',',$sequenceArray); $config->set($csValueKey,$csValue); } } $safePath = trim($config->get('forSale_path')); if(!empty($safePath)){ if(DS!='/' and strpos($safePath,'/')!==false){ $safePath=str_replace('/',DS,$safePath); vmInfo('Corrected safe path, replaced / by '.DS); vmdebug('$safePath',$safePath); } $length = strlen($safePath); if(strrpos($safePath,DS)!=($length-1)){ $safePath = $safePath.DS; vmInfo('Corrected safe path, added missing '.DS); } $config->set('forSale_path',$safePath); } else { $safePath = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'vmfiles'; $exists = JFolder::exists($safePath); if(!$exists){ $created = JFolder::create($safePath); $safePath = $safePath.DS; if($created){ vmInfo('COM_VIRTUEMART_SAFE_PATH_DEFAULT_CREATED',$safePath); /* create htaccess file */ $fileData = "order deny, allow\ndeny from all\nallow from none"; JLoader::import('joomla.filesystem.file'); $fileName = $safePath.DS.'.htaccess'; $result = JFile::write($fileName, $fileData); if (!$result) { VmWarn('COM_VIRTUEMART_HTACCESS_DEFAULT_NOT_CREATED',$safePath,$fileData); } $config->set('forSale_path',$safePath); } else { VmWarn('COM_VIRTUEMART_WARN_SAFE_PATH_NO_INVOICE',JText::_('COM_VIRTUEMART_ADMIN_CFG_MEDIA_FORSALE_PATH')); } } } if(!class_exists('shopfunctions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'shopfunctions.php'); $safePath = shopFunctions::checkSafePath($safePath); if(!empty($safePath)){ $exists = JFolder::exists($safePath.'invoices'); if(!$exists){ $created = JFolder::create($safePath.'invoices'); if($created){ vmInfo('COM_VIRTUEMART_SAFE_PATH_INVOICE_CREATED'); } else { VmWarn('COM_VIRTUEMART_WARN_SAFE_PATH_NO_INVOICE',JText::_('COM_VIRTUEMART_ADMIN_CFG_MEDIA_FORSALE_PATH')); } } } if(!$config->get('active_languages',false)){ $confData['active_languages'] = array(VmConfig::$langTag); } $confData['config'] = $config->toString(); $confTable = $this->getTable('configs'); if (!$confTable->bindChecknStore($confData)) { vmError($confTable->getError()); } // Load the newly saved values into the session. $config = VmConfig::loadConfig(true); if(!class_exists('GenericTableUpdater')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'tableupdater.php'); $updater = new GenericTableUpdater(); $result = $updater->createLanguageTables(); /* This conditions is not enough, if the language changes we need to recall the cache. $newbrowse_cat_orderby_field = $config->get('browse_cat_orderby_field'); $newcat_brws_orderby_dir = $config->get('cat_brws_orderby_dir'); if($browse_cat_orderby_field!=$newbrowse_cat_orderby_field or $newcat_brws_orderby_dir!=$cat_brws_orderby_dir){ $cache = JFactory::getCache('com_virtuemart_cats','callback'); $cache->clean(); }*/ $cache = JFactory::getCache('com_virtuemart_cats','callback'); $cache->clean(); $cache = JFactory::getCache('com_virtuemart_rss','callback'); $cache->clean(); $cache = JFactory::getCache('convertECB','callback'); $cache->clean(); $cache = JFactory::getCache('_virtuemart'); $cache->clean(); $cache = JFactory::getCache('com_plugins'); $cache->clean(); $cache = JFactory::getCache('_system'); $cache->clean(); $cache = JFactory::getCache('page'); $cache->clean(); return true; } public static function checkConfigTableExists(){ $db = JFactory::getDBO(); $query = 'SHOW TABLES LIKE "'.$db->getPrefix().'virtuemart_configs"'; $db->setQuery($query); $configTable = $db->loadResult(); $err = $db->getErrorMsg(); if(!empty($err) or !$configTable){ return false; } else { return true; } } static public function checkVirtuemartInstalled(){ $db = JFactory::getDBO(); $query = 'SHOW TABLES LIKE "'.$db->getPrefix().'virtuemart%"'; $db->setQuery($query); $vmTables = $db->loadColumn(); $err = $db->getErrorMsg(); if(!empty($err) or !$vmTables or count($vmTables)<2){ return false; } else { return true; } } /** * Dangerous tools get disabled after execution an operation which needed that rights. * This is the function actually doing it. * * @author Max Milbers */ function setDangerousToolsOff(){ if(self::checkConfigTableExists()){ $dangerousTools = VmConfig::readConfigFile(true); if( $dangerousTools){ $uri = JFactory::getURI(); $link = $uri->root() . 'administrator/index.php?option=com_virtuemart&view=config'; $lang = JText::sprintf('COM_VIRTUEMART_SYSTEM_DANGEROUS_TOOL_STILL_ENABLED',JText::_('COM_VIRTUEMART_ADMIN_CFG_DANGEROUS_TOOLS'),$link); VmInfo($lang); } else { $data['dangeroustools'] = 0; $data['virtuemart_config_id'] = 1; $this->store($data); } } } public function remove() { $table = $this->getTable('configs'); $id = 1; if (!$table->delete($id)) { vmError(get_class( $this ).'::remove '.$id.' '.$table->getError(),'Cannot delete config'); return false; } return true; } /** * This function deletes a config stored in the database * * @author Max Milbers */ function deleteConfig(){ if($this->remove()){ return VmConfig::loadConfig(true,true); } else { return false; } } } //pure php no closing taguserfields.php000066600000126177151372127700007451 0ustar00fieldname with formfields that are saved as parameters */ var $reqParam; // stAn, this variable is a cached result of getUserFields // where array key is $cache_hash = md5($sec.serialize($_switches).serialize($_skip).$this->_selectedOrdering.$this->_selectedOrderingDir); static $_cache_ordered; // this variable is a cached result of named fields of last call of getUserFields where the key is $_sec of the function ('registration', 'account', 'shipping'.. etc...) // example $_cached_named['registration']['email'] static $_cache_named; // *** code for htmlpurifier *** // var $htmlpurifier = ''; /** * constructs a VmModel * setMainTable defines the maintable of the model * @author Max Milbers */ function __construct() { parent::__construct('virtuemart_userfield_id'); $this->setMainTable('userfields'); $this->setToggleName('required'); $this->setToggleName('registration'); $this->setToggleName('shipment'); $this->setToggleName('account'); // Instantiate the Helper class $this->_params = new ParamHelper(); self::$_cache_ordered = null; self::$_cache_named = array(); // Form fields that must be translated to parameters $this->reqParam = array ( 'age_verification' => 'minimum_age' ,'euvatid' => 'virtuemart_shoppergroup_id' ,'webaddress' => 'webaddresstype' ); $this->_selectedOrdering = 'ordering'; $this->_selectedOrderingDir = 'ASC'; } /** * Prepare a user field for database update */ public function prepareFieldDataSave($field, &$data) { // $post = JRequest::get('post'); $fieldType = $field->type; $fieldName = $field->name; $value = $data[$field->name]; $params = $field->params; if(!class_exists('vmFilter'))require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmfilter.php'); switch(strtolower($fieldType)) { case 'webaddress': if (isset($post[$fieldName."Text"]) && ($post[$fieldName."Text"])) { $oValuesArr = array(); $oValuesArr[0] = str_replace(array('mailto:','http://','https://'),'', $value); $oValuesArr[1] = str_replace(array('mailto:','http://','https://'),'', $post[$fieldName."Text"]); $value = implode("|*|",$oValuesArr); } else { if ($value = vmFilter::urlcheck($value) ) $value = str_replace(array('mailto:','http://','https://'),'', $value); } break; case 'email': case 'emailaddress': //vmdebug('emailaddress before filter',$value); $value = vmFilter::mail( $value ); //$value = str_replace('mailto:','', $value); //$value = str_replace(array('\'','"',',','%','*','/','\\','?','^','`','{','}','|','~'),array(''),$value); //vmdebug('emailaddress after filter',$value); break; // case 'phone': // $value = vmFilter::phone( $value ); // break; case 'multiselect': case 'multicheckbox': case 'select': if (is_array($value)) $value = implode("|*|",$value); break; case 'age_verification': $value = JRequest::getInt('birthday_selector_year') .'-'.JRequest::getInt('birthday_selector_month') .'-'.JRequest::getInt('birthday_selector_day'); break; case 'textarea': $value = JRequest::getVar($fieldName, '', 'post', 'string' ,JREQUEST_ALLOWRAW); $value = vmFilter::hl( $value,'text' ); break; case 'editorta': $value = JRequest::getVar($fieldName, '', 'post', 'string' ,JREQUEST_ALLOWRAW); $value = vmFilter::hl( $value,'no_js_flash' ); break; default: // //*** code for htmlpurifier *** // //SEE http://htmlpurifier.org/ // // must only add all htmlpurifier in library/htmlpurifier/ // if (!$this->htmlpurifier) { // require(JPATH_VM_ADMINISTRATOR.DS.'library'.DS.'htmlpurifier'.DS.'HTMLPurifier.auto.php'); // $config = HTMLPurifier_Config::createDefault(); // $this->htmlpurifier = new HTMLPurifier($config); // } // $value = $this->htmlpurifier->purify($value); // vmdebug( "purified filter" , $value); //$config->set('URI.HostBlacklist', array('google.com'));// set eg .add google.com in black list if (strpos($fieldType,'plugin')!==false){ JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); // vmdebug('params',$params); $dispatcher->trigger('plgVmPrepareUserfieldDataSave',array($fieldType, $fieldName, &$data, &$value, $params) ); return $value; } // no HTML TAGS but permit all alphabet $value = vmFilter::hl( $value,array('deny_attribute'=>'*')); $value = preg_replace('@<[\/\!]*?[^<>]*?>@si','',$value);//remove all html tags $value = (string)preg_replace('#on[a-z](.+?)\)#si','',$value);//replace start of script onclick() onload()... $value = trim(str_replace('"', ' ', $value),"'") ; $value = (string)preg_replace('#^\'#si','',$value);//replace ' at start break; } return $value; } /** * Retrieve the detail record for the current $id if the data has not already been loaded. */ function getUserfield($id = 0,$name = 0) { if($id === 0){ $id = $this->_id; } if (empty($this->_data)) { $this->_data = $this->getTable('userfields'); if($name !==0){ $this->_data->load($id, $name); } $this->_data->load($id); } if(strpos($this->_data->type,'plugin')!==false){ JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $plgName = substr($this->_data->type,6); $type = 'userfield'; $retValue = $dispatcher->trigger('plgVmDeclarePluginParamsUserfield',array($type,$plgName,$this->_data->userfield_jplugin_id,&$this->_data)); // vmdebug('pluginGet',$type,$plgName,$this->_id,$this->_data); } // Parse the parameters, if any else $this->_params->parseParam($this->_data->params); return $this->_data; } /** * Retrieve the value records for the current $id if available for the current type * * Updated by stAn to get userfieldvalues per specific id regardless on this->_id * * @return array List wil values, or an empty array if none exist */ function getUserfieldValues($id=null) { if (empty($id)) $id = $this->_id; $this->_data = $this->getTable('userfield_values'); if ($id > 0) { $query = 'SELECT * FROM `#__virtuemart_userfield_values` WHERE `virtuemart_userfield_id` = ' . (int)$id . ' ORDER BY `ordering`'; $_userFieldValues = $this->_getList($query); return $_userFieldValues; } else { return array(); } } static function getCoreFields(){ return array( 'name','username', 'email', 'password', 'password2' , 'agreed','language'); } /** * Bind the post data to the userfields table and save it * * @return boolean True is the save was successful, false otherwise. */ function store(&$data){ $field = $this->getTable('userfields'); $userinfo = $this->getTable('userinfos'); $orderinfo = $this->getTable('order_userinfos'); $isNew = ($data['virtuemart_userfield_id'] < 1) ? true : false; $coreFields = $this->getCoreFields(); if(in_array($data['name'],$coreFields)){ //vmError('Cant store/update core field. They belong to joomla'); //return false; } else { if ($isNew) { $reorderRequired = false; $_action = 'ADD'; } else { $field->load($data['virtuemart_userfield_id']); $_action = 'CHANGE'; if ($field->ordering == $data['ordering']) { $reorderRequired = false; } else { $reorderRequired = true; } } } //vmdebug ('SAVED userfields', $data); // Put the parameters, if any, in the correct format if (array_key_exists($data['type'], $this->reqParam)) { $this->_params->set($this->reqParam[$data['type']], $data[$this->reqParam[$data['type']]]); $data['params'] = $this->_params->paramString(); } // Store the fieldvalues, if any, in a correct array $fieldValues = $this->postData2FieldValues($data['vNames'], $data['vValues'], $data['virtuemart_userfield_id'] ); if(strpos($data['type'],'plugin')!==false){ // missing string FIX, Bad way ? if (JVM_VERSION===1) { $tb = '#__plugins'; $ext_id = 'id'; } else { $tb = '#__extensions'; $ext_id = 'extension_id'; } $plgName = substr($data['type'],6); $q = 'SELECT `' . $ext_id . '` FROM `' . $tb . '` WHERE `element` = "'.$plgName.'"'; $this->_db->setQuery($q); $data['userfield_jplugin_id'] = $this->_db->loadResult(); JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('plgVmOnBeforeUserfieldSave',array( $plgName , &$data, &$field ) ); } if (!$field->bind($data)) { // Bind data vmError($field->getError()); return false; } if (!$field->check(count($fieldValues))) { // Perform data checks //vmError($field->getError()); return false; } // Get the fieldtype for the database $_fieldType = $field->formatFieldType($data); if(!in_array($data['name'],$coreFields) && $field->type != 'delimiter'){ // Alter the user_info table if (!$userinfo->_modifyColumn ($_action, $data['name'], $_fieldType)) { vmError('userfield store modifyColumn userinfo',$userinfo->getError()); return false; } // Alter the order_userinfo table if (!$orderinfo->_modifyColumn ($_action, $data['name'], $_fieldType)) { vmError('userfield store modifyColumn orderinfo',$orderinfo->getError()); return false; } } // if new item, order last in appropriate group if ($isNew) { $field->ordering = $field->getNextOrder(); } $_id = $field->store(); if ($_id === false) { // Write data to the DB vmError($field->getError()); return false; } if (!$this->storeFieldValues($fieldValues, $_id)) { return false; } if(strpos($data['type'],'plugin')!==false){ JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $plgName = substr($data['type'],6); $dispatcher->trigger('plgVmOnStoreInstallPluginTable',array( 'userfield' , $data ) ); } if ($reorderRequired) { $field->reorder(); } vmdebug('storing userfield',$_id); // Alter the user_info database to hold the values return $_id; } /** * Bind and write all value records * * @param array $_values * @param mixed $_id If a new record is being inserted, it contains the virtuemart_userfield_id, otherwise the value true * @return boolean */ private function storeFieldValues($_values, $_id) { // stAn - not true, because if previously we had more values, we have to delete them /* if (count($_values) == 0) { return true; //Nothing to do } */ $fieldvalue = $this->getTable('userfield_values'); // get original values $originalvalues = $this->getUserfieldValues($_id); // for each orignal value search if it was deleted or modified for ($i = 0; $i < count($originalvalues); $i++) { if (isset($_values[$i])) { if (!($_id === true)) { // If $_id is true, it was not a new record $_values[$i]['virtuemart_userfield_id'] = $_id; } if (!$fieldvalue->bind($_values[$i])) { // Bind data vmError($fieldvalue->getError()); return false; } if (!$fieldvalue->check()) { // Perform data checks vmError($fieldvalue->getError()); return false; } if (!$fieldvalue->store()) { // Write data to the DB vmError($fieldvalue->getError()); return false; } } else { // the field was deleted // stAn, next line doesn't work, because it tries to delete by the virtuemart_userfield_id instead of virtuemart_userfield_value_id // $msg = $fieldvalue->delete($originalvalues->virtuemart_userfield_value_id); $db = JFactory::getDBO(); $q = 'DELETE from `#__virtuemart_userfield_values` WHERE `virtuemart_userfield_value_id` = ' . (int)$originalvalues[$i]->virtuemart_userfield_value_id.' and `virtuemart_userfield_id` = '.(int)$_id; $db->setQuery($q); if ($db->query() === false) { vmError($db->getError()); return false; } } } // for each new value that was added for ($i = count($originalvalues)-1; $i < count($_values) ; $i++) { // do a check here as we might not be using pure numeric arrays if (isset($_values[$i])) { if (!($_id === true)) { // If $_id is true, it was not a new record $_values[$i]['virtuemart_userfield_id'] = $_id; } if (!$fieldvalue->bind($_values[$i])) { // Bind data vmError($fieldvalue->getError()); return false; } if (!$fieldvalue->check()) { // Perform data checks vmError($fieldvalue->getError()); return false; } if (!$fieldvalue->store()) { // Write data to the DB vmError($fieldvalue->getError()); return false; } } } return true; } /** * * @author Max Milbers */ public function getUserFieldsFor($layoutName, $type,$userId = -1){ //vmdebug('getUserFieldsFor '.$layoutName.' '. $type .' ' . $userId); $register = false; if(VmConfig::get('oncheckout_show_register',1) and $type=='BT'){ $user = JFactory::getUser(); if(!empty($user)){ if(empty($user->id)){ $register = true; } } else { $register = true; } } else { $register = false; } $skips = array(); //Maybe there is another method to define the skips $skips = array('address_type'); if((!$register or $type =='ST') and $layoutName !='edit'){ $skips[] = 'name'; $skips[] = 'username'; $skips[] = 'password'; $skips[] = 'password2'; $skips[] = 'user_is_vendor'; $skips[] = 'agreed'; // MattLG: Added this line because it leaves the empty fieldset with just the label when editing the ST addresses // A better solution might be to make this a setting rather than hard coding this whole block here $skips[] = 'delimiter_userinfo'; } //Here we get the fields if ($type == 'BT') { $userFields = $this->getUserFields( 'account' , array() // Default toggles , $skips// Skips ); } else { $userFields = $this->getUserFields( 'shipment' , array() // Default toggles , $skips ); } //Small ugly hack to make registering optional //do we still need that? YES ! notice by Max Milbers if($register && $type == 'BT' && VmConfig::get('oncheckout_show_register',1) ){ $corefields = $this->getCoreFields(); unset($corefields[2]); //the 2 is for the email field, it is necessary in almost anycase. foreach($userFields as $field){ if(in_array($field->name,$corefields)){ $field->required = 0; $field->value = ''; $field->default = ''; } } } return $userFields; } /** * Retrieve an array with userfield objects * * @param string $section The section the fields belong to (e.g. 'registration' or 'account') * @param array $_switches Array to toggle these options: * * published published fields only (default: true) * * required Required fields only (default: false) * * delimiters Exclude delimiters (default: false) * * captcha Exclude Captcha type (default: false) * * system System fields filter (no default; true: only system fields, false: exclude system fields) * @param array $_skip Array with fieldsnames to exclude. Default: array('username', 'password', 'password2', 'agreed'), * specify array() to skip nothing. * @see getUserFieldsFilled() * @author Oscar van Eijk * @return array */ public function getUserFields ($_sec = 'registration', $_switches=array(), $_skip = array('username', 'password', 'password2')) { // stAn, we can't really create cache per sql as we want to create named array as well $cache_hash = md5($_sec.serialize($_switches).serialize($_skip).$this->_selectedOrdering.$this->_selectedOrderingDir); if (isset(self::$_cache_ordered[$cache_hash])) return self::$_cache_ordered[$cache_hash]; $_q = 'SELECT * FROM `#__virtuemart_userfields` WHERE 1 = 1 '; if( $_sec != 'bank' && $_sec != '') { $_q .= 'AND `'.$_sec.'`=1 '; } elseif ($_sec == 'bank' ) { $_q .= "AND name LIKE '%bank%' "; } /* if (($_skipBank = array_search('bank', $_skip)) !== false ) { $_q .= "AND name NOT LIKE '%bank%' "; unset ($_skip[$_skipBank]); }*/ if(array_key_exists('published',$_switches)){ if ($_switches['published'] !== false ) { $_q .= 'AND published = 1 '; } } else { $_q .= 'AND published = 1 '; } if(array_key_exists('required',$_switches)){ if ($_switches['required'] === true ) { $_q .= "AND required = 1 "; } } if(array_key_exists('delimiters',$_switches)){ if ($_switches['delimiters'] === true ) { $_q .= "AND type != 'delimiter' "; } } if(array_key_exists('captcha',$_switches)){ if ($_switches['captcha'] === true ) { $_q .= "AND type != 'captcha' "; } } if(array_key_exists('sys',$_switches)){ if ($_switches['sys'] === true ) { $_q .= "AND sys = 1 "; } else { $_q .= "AND sys = 0 "; } } if (count($_skip) > 0) { $_q .= "AND FIND_IN_SET(name, '".implode(',', $_skip)."') = 0 "; } $_q .= ' ORDER BY ordering '; $_fields = $this->_getList($_q); // We need some extra fields that are not in the userfields table. They will be hidden on the details form if (!in_array('address_type', $_skip)) { $_address_type = new stdClass(); $_address_type->virtuemart_userfield_id = 0; $_address_type->name = 'address_type'; $_address_type->title = ''; $_address_type->description = '' ; $_address_type->type = 'hidden'; $_address_type->maxlength = 0; $_address_type->size = 0; $_address_type->required = 0; $_address_type->ordering = 0; $_address_type->cols = 0; $_address_type->rows = 0; $_address_type->value = ''; $_address_type->default = 'BT'; $_address_type->published = 1; $_address_type->registration = 1; $_address_type->shipment = 0; $_address_type->account = 1; $_address_type->readonly = 0; $_address_type->calculated = 0; // what is this??? $_address_type->sys = 0; $_address_type->virtuemart_vendor_id = 1; $_address_type->params = ''; $_fields[] = $_address_type; } // stAn: slow to run the first time: self::$_cache_ordered[$cache_hash] = $_fields; if (!isset(self::$_cache_named[$_sec])) self::$_cache_named[$_sec] = array(); foreach ($_fields as &$f) { self::$_cache_named[$_sec][$f->name] = $f; } return $_fields; } /** * Return a boolean whethe the userfield is enabled in context of $_sec * * @access public * @param $_field_name: name of the user field such as 'email' * @param $_sec BT or ST, or one of the types of the fields: account, shipment, registration * @author stAn * @return true or false * * Note: this function will return a false result for skipped fields such as agreed, user_is_vendor * * when used from shipment method, you can use * $userFieldsModel =VmModel::getModel('Userfields'); * $type = (($cart->ST == 0) ? 'BT' : 'ST'); * if ($userFieldsModel->fieldPublished('zip', $type)) .... */ public function fieldPublished($_field_name, $_sec='account') { if ($_sec == 'BT') $_sec = 'account'; else if ($_sec == 'ST') $_sec = 'shipment'; if (isset(self::$_cache_named[$_sec])) return isset(self::$_cache_named[$_sec][$_field_name]); $this->getUserFields($_sec, array(), array()); if (isset(self::$_cache_named[$_sec])) return isset(self::$_cache_named[$_sec][$_field_name]); return false; } /** * Return an array with userFields in several formats. * * @access public * @param $_selection An array, as returned by getuserFields(), with fields that should be returned. * @param $_userData Array with userdata holding the values for the fields * @param $_prefix string Optional prefix for the formtag name attribute * @author Oscar van Eijk * @return array List with all userfield data in the format: * array( * 'fields' => array( // All fields * => array( * 'name' => // Name of the field * 'value' => // Existing value for the current user, or the default * 'title' => // Title used for label and such * 'type' => // Field type as specified in the userfields table * 'hidden' => // True/False * 'required' => // True/False. If True, the formcode also has the class "required" for the Joomla formvalidator * 'formcode' => // Full HTML tag * ) * [...] * ) * 'functions' => array() // Optional javascript functions without ; * 'scripts' => array( // Array with scriptsources for use with JHTML::script(); * => * [...] * ) * 'links' => array( // Array with stylesheets for use with JHTML::stylesheet(); * => * [...] * ) * ) * @example This example illustrates the use of this function. For additional examples, see the Order view * and the User view in the administrator section. *
	 *   // In the controller, make sure this model is loaded.
	 *   // In view.html.php, make the following calls:
	 *   $_usrDetails = getUserDetailsFromSomeModel(); // retrieve an user_info record, eg from the usermodel or ordermodel
	 *   $_usrFieldList = $userFieldsModel->getUserFields(
	 *                    'registration'
	 *                  , array() // Default switches
	 *                  , array('delimiter_userinfo', 'username', 'email', 'password', 'password2', 'agreed', 'address_type') // Skips
	 *    );
	 *   $usrFieldValues = $userFieldsModel->getUserFieldsFilled(
	 *                      $_usrFieldList
	 *                     ,$_usrDetails
	 *   );
	 *   $this->assignRef('userfields', $userfields);
	 *   // In the template, use code below to display the data. For an extended example using
	 *   // delimiters, JavaScripts and StyleSheets, see the edit_shopper.php in the user view
	 *   
	 *     
	 *       
	 *         
	 *       
	 *     
	 *      shipmentfields['fields'] as $_field ) {
	 *          echo '  '."\n";
	 *          echo '    '."\n";
	 *          echo '    '."\n";
	 *          echo '  '."\n";
	 *        }
	 *      ?>
	 *    
* *
'."\n"; * echo ' '.$_field['title']."\n"; * echo ' '."\n"; * * echo ' '.$_field['value']."\n"; // Display only * Or: * echo ' '.$_field['formcode']."\n"; // Input form * * echo '
*
*/ public function getUserFieldsFilled($_selection, $_userData = null, $_prefix = ''){ if(!class_exists('ShopFunctions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'shopfunctions.php'); $_return = array( 'fields' => array() ,'functions' => array() ,'scripts' => array() ,'links' => array() ); $admin = false; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(Permissions::getInstance()->check('admin','storeadmin')){ $admin = true; } // vmdebug('my user data in getUserFieldsFilled',$_selection,$_userData); $_userData=(array)($_userData); if (is_array($_selection)) { foreach ($_selection as $_fld) { $_return['fields'][$_fld->name] = array( 'name' => $_prefix . $_fld->name ,'value' => (($_userData == null || !array_key_exists($_fld->name, $_userData)) ? $_fld->default : @html_entity_decode($_userData[$_fld->name],ENT_COMPAT,'UTF-8')) ,'title' => vmText::_($_fld->title) ,'type' => $_fld->type ,'required' => $_fld->required ,'hidden' => false ,'formcode' => '' ,'description' => vmText::_($_fld->description) ); $readonly = ''; if(!$admin){ if($_fld->readonly ){ $readonly = ' readonly="readonly" '; } } // vmdebug ('getUserFieldsFilled',$_fld->name); // if($_fld->name==='email') vmdebug('user data email getuserfieldbyuser',$_userData); // First, see if there are predefined fields by checking the name switch( $_fld->name ) { // case 'email': // $_return['fields'][$_fld->name]['formcode'] = $_userData->email; // break; case 'virtuemart_country_id': $attrib = array(); //For nice lists in the FE if ($_fld->size) { $attrib = array('style'=>"width: ".$_fld->size."px"); } $_return['fields'][$_fld->name]['formcode'] = ShopFunctions::renderCountryList($_return['fields'][$_fld->name]['value'], false, $attrib , $_prefix, $_fld->required); if(!empty($_return['fields'][$_fld->name]['value'])){ // Translate the value from ID to name $_return['fields'][$_fld->name]['virtuemart_country_id'] = (int)$_return['fields'][$_fld->name]['value']; $db = JFactory::getDBO (); $q = 'SELECT * FROM `#__virtuemart_countries` WHERE virtuemart_country_id = "' . (int)$_return['fields'][$_fld->name]['value'] . '"'; $db->setQuery ($q); $r = $db->loadAssoc(); if($r){ $_return['fields'][$_fld->name]['value'] = !empty($r['country_name'])? $r['country_name']:'' ; $_return['fields'][$_fld->name]['country_2_code'] = !empty($r['country_2_code'])? $r['country_2_code']:'' ; $_return['fields'][$_fld->name]['country_3_code'] = !empty($r['country_3_code'])? $r['country_3_code']:'' ; } else { vmError('Model Userfields, country with id '.$_return['fields'][$_fld->name]['value'].' not found'); } } else { $_return['fields'][$_fld->name]['value'] = '' ; $_return['fields'][$_fld->name]['country_2_code'] = '' ; $_return['fields'][$_fld->name]['country_3_code'] = '' ; } //$_return['fields'][$_fld->name]['value'] = JText::_(shopFunctions::getCountryByID($_return['fields'][$_fld->name]['value'])); //$_return['fields'][$_fld->name]['state_2_code'] = JText::_(shopFunctions::getCountryByID($_return['fields'][$_fld->name]['value'])); break; case 'virtuemart_state_id': if (!class_exists ('shopFunctionsF')) require(JPATH_VM_SITE . DS . 'helpers' . DS . 'shopfunctionsf.php'); $attrib = array(); if ($_fld->size) { $attrib = array('style'=>"width: ".$_fld->size."px"); } $_return['fields'][$_fld->name]['formcode'] = shopFunctions::renderStateList( $_return['fields'][$_fld->name]['value'], $_prefix, false, $_fld->required, $attrib ); if(!empty($_return['fields'][$_fld->name]['value'])){ // Translate the value from ID to name $_return['fields'][$_fld->name]['virtuemart_state_id'] = (int)$_return['fields'][$_fld->name]['value']; $db = JFactory::getDBO (); $q = 'SELECT * FROM `#__virtuemart_states` WHERE virtuemart_state_id = "' . (int)$_return['fields'][$_fld->name]['value'] . '"'; $db->setQuery ($q); $r = $db->loadAssoc(); if($r){ $_return['fields'][$_fld->name]['value'] = !empty($r['state_name'])? $r['state_name']:'' ; $_return['fields'][$_fld->name]['state_2_code'] = !empty($r['state_2_code'])? $r['state_2_code']:'' ; $_return['fields'][$_fld->name]['state_3_code'] = !empty($r['state_3_code'])? $r['state_3_code']:'' ; } else { vmError('Model Userfields, state with id '.$_return['fields'][$_fld->name]['value'].' not found'); } } else { $_return['fields'][$_fld->name]['value'] = '' ; $_return['fields'][$_fld->name]['state_2_code'] = '' ; $_return['fields'][$_fld->name]['state_3_code'] = '' ; } //$_return['fields'][$_fld->name]['value'] = shopFunctions::getStateByID($_return['fields'][$_fld->name]['value']); break; //case 'agreed': // $_return['fields'][$_fld->name]['formcode'] = 'required ? ' class="required"' : '') . ' />'; // break; case 'password': case 'password2': $_return['fields'][$_fld->name]['formcode'] = ''."\n"; break; case 'agreed': $_return['fields'][$_fld->name]['formcode'] = 'name]['value'] ? 'checked="checked"' : '') .'/>'; break; // It's not a predefined field, so handle it by it's fieldtype default: if(strpos($_fld->type,'plugin')!==false){ JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('plgVmOnUserfieldDisplay',array($_prefix, $_fld,isset($_userData['virtuemart_user_id'])?$_userData['virtuemart_user_id']:0, &$_return) ); break; } switch( $_fld->type ) { case 'hidden': $_return['fields'][$_fld->name]['formcode'] = 'required ? ' class="required"' : '') . ($_fld->maxlength ? ' maxlength="' . $_fld->maxlength . '"' : '') . $readonly . ' /> '; $_return['fields'][$_fld->name]['hidden'] = true; break; case 'date': case 'age_verification': //echo JHTML::_('behavior.calendar'); /* * TODO We must add the joomla.javascript here that contains the calendar, * since Joomla does not load it when there's no user logged in. * Gotta find out why... some security issue or a bug??? * Note by Oscar */ // if ($_userData === null) { // Not logged in // $_doc = JFactory::getDocument(); // $_doc->addScript( JURI::root(true).'/includes/js/joomla.javascript.js'); // } $currentYear= date('Y'); // $calendar = vmJsApi::jDate($_return['fields'][$_fld->name]['value'], $_prefix.$_fld->name, $_prefix.$_fld->name . '_field',false,($currentYear-100).':'.$currentYear); // $_return['fields'][$_fld->name]['formcode'] = $calendar ; //if(empty($_return['fields'][$_fld->name]['value'])){ // $_return['fields'][$_fld->name]['value'] = "1912-01-01 00:00:00"; //} jDate($date='',$name="date",$id=null,$resetBt = true, $yearRange='') { // Year range MUST start 100 years ago, for birthday $_return['fields'][$_fld->name]['formcode'] = vmJsApi::jDate($_return['fields'][$_fld->name]['value'], $_prefix.$_fld->name,$_prefix.$_fld->name . '_field',false,($currentYear-100).':'.$currentYear); break; case 'emailaddress': if( JFactory::getApplication()->isSite()) { if(empty($_return['fields'][$_fld->name]['value'])) { $_return['fields'][$_fld->name]['value'] = JFactory::getUser()->email; } } // vmdebug('emailaddress',$_fld); case 'text': case 'webaddress': $_return['fields'][$_fld->name]['formcode'] = 'required ? ' class="required"' : '') . ($_fld->maxlength ? ' maxlength="' . $_fld->maxlength . '"' : '') . $readonly . ' /> '; break; case 'textarea': $_return['fields'][$_fld->name]['formcode'] = ''; break; case 'editorta': jimport( 'joomla.html.editor' ); $editor = JFactory::getEditor(); $_return['fields'][$_fld->name]['formcode'] = $editor->display($_prefix.$_fld->name, $_return['fields'][$_fld->name]['value'], '150', '100', $_fld->cols, $_fld->rows, array('pagebreak', 'readmore')); break; case 'checkbox': $_return['fields'][$_fld->name]['formcode'] = 'name]['value'] ? 'checked="checked"' : '') .'/>'; if($_return['fields'][$_fld->name]['value']) { $_return['fields'][$_fld->name]['value'] = JText::_($_prefix.$_fld->title); } break; // /*##mygruz20120223193710 { :*/ // case 'userfieldplugin': //why not just vmuserfieldsplugin ? // JPluginHelper::importPlugin('vmuserfield'); // $dispatcher = JDispatcher::getInstance(); // //Todo to adjust to new pattern, using & // $html = '' ; // $dispatcher->trigger('plgVmOnUserFieldDisplay',array($_return['fields'][$_fld->name], &$html) ); // $_return['fields'][$_fld->name]['formcode'] = $html; // break; // /*##mygruz20120223193710 } */ case 'multicheckbox': case 'multiselect': case 'select': case 'radio': $_qry = 'SELECT fieldtitle, fieldvalue ' . 'FROM #__virtuemart_userfield_values ' . 'WHERE virtuemart_userfield_id = ' . $_fld->virtuemart_userfield_id . ' ORDER BY ordering '; $_values = $this->_getList($_qry); // We need an extra lok here, especially for the Bank info; the values // must be translated. // Don't check on the field name though, since others might be added in the future :-( foreach ($_values as $_v) { $_v->fieldtitle = vmText::_($_v->fieldtitle); } $_attribs = array(); if ($_fld->readonly and !$admin) { $_attribs['readonly'] = 'readonly'; } if ($_fld->required) { $_attribs['class'] = 'required'; } if ($_fld->type == 'radio' or $_fld->type == 'select') { $_selected = $_return['fields'][$_fld->name]['value']; } else { $_attribs['size'] = $_fld->size; // Use for all but radioselects if (!is_array($_return['fields'][$_fld->name]['value'])){ $_selected = explode("|*|", $_return['fields'][$_fld->name]['value']); } else { $_selected = $_return['fields'][$_fld->name]['value']; } } // Nested switch... switch($_fld->type) { case 'multicheckbox': // todo: use those $_attribs['rows'] = $_fld->rows; $_attribs['cols'] = $_fld->cols; $formcode = ''; $field_values=""; $_idx = 0; $separator_form = '
'; $separator_title = ','; foreach ($_values as $_val) { if ( in_array($_val->fieldvalue, $_selected)) { $is_selected='checked="checked"'; $field_values.= JText::_($_val->fieldtitle). $separator_title; } else { $is_selected=''; } $formcode .= ' '. $separator_form; $_idx++; } // remove last br $_return['fields'][$_fld->name]['formcode'] =substr($formcode ,0,-strlen($separator_form)); $_return['fields'][$_fld->name]['value'] = substr($field_values,0,-strlen($separator_title)); break; case 'multiselect': $_attribs['multiple'] = 'multiple'; $_attribs['class'] = 'vm-chzn-select'; $field_values=""; $_return['fields'][$_fld->name]['formcode'] = JHTML::_('select.genericlist', $_values, $_prefix.$_fld->name.'[]', $_attribs, 'fieldvalue', 'fieldtitle', $_selected); $separator_form = '
'; $separator_title = ','; foreach ($_values as $_val) { if ( in_array($_val->fieldvalue, $_selected)) { $field_values.= JText::_($_val->fieldtitle). $separator_title; } } $_return['fields'][$_fld->name]['value'] = substr($field_values,0,-strlen($separator_title)); break; case 'select': $_attribs['class'] = 'vm-chzn-select'; if ($_fld->size) { $_attribs['style']= "width: ".$_fld->size."px"; } if(!$_fld->required){ $obj = new stdClass(); $obj->fieldtitle = vmText::_('COM_VIRTUEMART_LIST_EMPTY_OPTION'); $obj->fieldvalue = ''; array_unshift($_values,$obj); } $_return['fields'][$_fld->name]['formcode'] = JHTML::_('select.genericlist', $_values, $_prefix.$_fld->name, $_attribs, 'fieldvalue', 'fieldtitle', $_selected); foreach ($_values as $_val) { if ( !empty($_selected) and $_val->fieldvalue==$_selected ) { // vmdebug('getUserFieldsFilled set empty select to value',$_selected,$_fld,$_return['fields'][$_fld->name]); $_return['fields'][$_fld->name]['value'] = vmText::_($_val->fieldtitle); } } break; case 'radio': $_return['fields'][$_fld->name]['formcode'] = JHTML::_('select.radiolist', $_values, $_prefix.$_fld->name, $_attribs, 'fieldvalue', 'fieldtitle', $_selected); foreach ($_values as $_val) { if ( $_val->fieldvalue==$_selected) { $_return['fields'][$_fld->name]['value'] = vmText::_($_val->fieldtitle); } } break; } break; } break; } } } else { vmdebug('getUserFieldsFilled $_selection is not an array ',$_selection); // $_return['fields'][$_fld->name]['formcode'] = ''; } return $_return; } /** * Checks if a single field is required, used in the cart * * @author Max Milbers * @param string $fieldname */ function getIfRequired($fieldname) { $q = 'SELECT `required` FROM #__virtuemart_userfields WHERE `name` = "'.$fieldname.'" '; $this->_db->setQuery($q); $result = $this->_db->loadResult(); $error = $this->_db->getErrorMsg(); if(!empty($error)){ vmError('userfields getIfRequired '.$error,'Programmer used an unknown userfield '.$fieldname); } return $result; } /** * Translate arrays form userfield_values to the format expected by the table class. * * stAn Note -> when a field of [0] is deleted (or others), you cannot use count to itenerate the array * * @param array $titles List of titles from the formdata * @param array $values List of values from the formdata * @param int $virtuemart_userfield_id ID of the userfield to relate * @return array Data to bind to the userfield_values table */ private function postData2FieldValues($titles, $values, $virtuemart_userfield_id ){ $_values = array(); if (is_array($titles) && is_array($values)) { // updated by stAn: foreach ($values as $i=>$val) { $_values[$i] = array( 'virtuemart_userfield_id' => $virtuemart_userfield_id ,'fieldtitle' => $titles[$i] ,'fieldvalue' => $values[$i] ,'ordering' => $i ); } /* for ($i=0; $i < count($titles) ;$i++) { if (empty($titles[$i])) { continue; // Ignore empty fields } } */ } return $_values; } /** * Get the column name of a given fieldID * @param $_id integer Field ID * @return string Fieldname */ function getNameByID($_id) { $_sql = 'SELECT `name` FROM `#__virtuemart_userfields` WHERE virtuemart_userfield_id = "'.$_id.'" '; $_v = $this->_getList($_sql); return ($_v[0]->name); } /** * Delete all record ids selected * * @return boolean True is the remove was successful, false otherwise. */ function remove($fieldIds){ $field = $this->getTable('userfields'); $value = $this->getTable('userfield_values'); $userinfo = $this->getTable('userinfos'); $orderinfo = $this->getTable('order_userinfos'); $ok = true; foreach($fieldIds as $fieldId) { $_fieldName = $this->getNameByID($fieldId); $field->load($fieldId); if ($field->type != 'delimiter') { // Get the fieldtype for the database $_fieldType = $field->formatFieldType(); // Alter the user_info table if ($userinfo->_modifyColumn ('DROP', $_fieldName,$_fieldType) === false) { vmError($userinfo->getError()); $ok = false; } // Alter the order_userinfo table if ($orderinfo->_modifyColumn ('DROP', $_fieldName,$_fieldType) === false) { vmError($orderinfo->getError()); $ok = false; } } if (!$field->delete($fieldId)) { vmError($field->getError()); $ok = false; } if (!$value->delete($fieldId)) { vmError($field->getError()); $ok = false; } } return $ok; } /** * Get the userfields for the BE list * * @author Max Milbers * @return NULL */ function getUserfieldsList(){ if (!$this->_data) { $whereString = $this->_getFilter(); $ordering = $this->_getOrdering(); $this->_data = $this->exeSortSearchListQuery(0,'*',' FROM `#__virtuemart_userfields`',$whereString,'',$ordering); } return $this->_data; } /** * If a filter was set, get the SQL WHERE clase * * @return string text to add to the SQL statement */ function _getFilter() { $db = JFactory::getDBO(); if ($search = JRequest::getWord('search', false)) { $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; //$search = $this->_db->Quote($search, false); return (' WHERE `name` LIKE ' .$search); } return (''); } /** * Build the query to list all Userfields * *@deprecated * @return string SQL query statement */ function _getListQuery () { $query = 'SELECT * FROM `#__virtuemart_userfields` '; $query .= $this->_getFilter(); $query .= $this->_getOrdering(); return ($query); } //*/ } // No closing tag usergroups.php000066600000004011151372127700007500 0ustar00setMainTable('usergroups'); } function getUsergroup() { $db = JFactory::getDBO(); if (empty($this->_data)) { $this->_data = $this->getTable('usergroups'); $this->_data->load((int)$this->_id); } return $this->_data; } function getUsergroups($onlyPublished=false, $noLimit=false) { $where = array(); if ($onlyPublished) { $where[] = ' `#__virtuemart_shoppergroups`.`published` = 1'; } $whereString = ''; if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where) ; return $this->_data = $this->exeSortSearchListQuery(0,'*',' FROM `#__virtuemart_permgroups`',$whereString,'',$this->_getOrdering()); } } virtuemart.php000066600000010074151372127700007472 0ustar00_getListCount($query); } /** * Gets the total number of active products * * @author RickG * @return int Total number of active products in the database */ function getTotalActiveProducts() { $query = 'SELECT `virtuemart_product_id` FROM `#__virtuemart_products` WHERE `published`="1"'; return $this->_getListCount($query); } /** * Gets the total number of inactive products * * @author RickG * @return int Total number of inactive products in the database */ function getTotalInActiveProducts() { $query = 'SELECT `virtuemart_product_id` FROM `#__virtuemart_products` WHERE `published`="0"'; return $this->_getListCount($query); } /** * Gets the total number of featured products * * @author RickG * @return int Total number of featured products in the database */ function getTotalFeaturedProducts() { $query = 'SELECT `virtuemart_product_id` FROM `#__virtuemart_products` WHERE `product_special`="1"'; return $this->_getListCount($query); } /** * Gets the total number of orders with the given status * * @author RickG * @return int Total number of orders with the given status */ function getTotalOrdersByStatus() { $query = 'SELECT `#__virtuemart_orderstates`.`order_status_name`, `#__virtuemart_orderstates`.`order_status_code`, '; $query .= '(SELECT count(virtuemart_order_id) FROM `#__virtuemart_orders` WHERE `#__virtuemart_orders`.`order_status` = `#__virtuemart_orderstates`.`order_status_code`) as order_count '; $query .= 'FROM `#__virtuemart_orderstates`'; return $this->_getList($query); } /** * Gets a list of recent orders * * @author RickG * @return ObjectList List of recent orders. */ function getRecentOrders($nbrOrders=5) { $query = 'SELECT * FROM `#__virtuemart_orders` ORDER BY `created_on` desc'; return $this->_getList($query, 0, $nbrOrders); } /** * Gets a list of recent customers * * @author RickG * @return ObjectList List of recent orders. */ function getRecentCustomers($nbrCusts=5) { $query = 'SELECT `id` as `virtuemart_user_id`, `first_name`, `last_name`, `order_number` FROM `#__users` as `u` '; $query .= 'JOIN `#__virtuemart_vmusers` as uv ON u.id = uv.virtuemart_user_id '; $query .= 'JOIN `#__virtuemart_userinfos` as ui ON u.id = ui.virtuemart_user_id '; $query .= 'JOIN `#__virtuemart_orders` as uo ON u.id = uo.virtuemart_user_id '; $query .= 'WHERE `perms` <> "admin" '; $query .= 'AND `perms` <> "storeadmin" '; $query .= 'AND INSTR(`usertype`, "administrator") = 0 AND INSTR(`usertype`, "Administrator") = 0 '; $query .= ' ORDER BY uo.`created_on` DESC'; return $this->_getList($query, 0, $nbrCusts); } } //pure php no tagshoppergroup.php000066600000022335151372127700010030 0ustar00setMainTable('shoppergroups'); } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * * @author Markus Öhler */ function getShopperGroup() { if (empty($this->_data)) { $this->_data = $this->getTable('shoppergroups'); $this->_data->load((int) $this->_id); if(!empty($this->_data->price_display)){ $this->_data->price_display = unserialize($this->_data->price_display); } else{ if(!class_exists('JParameter')) require(JPATH_VM_LIBRARIES.DS.'joomla'.DS.'html'.DS.'parameter.php' ); $this->_data->price_display = new JParameter(''); } } return $this->_data; } /** * Retireve a list of shopper groups from the database. * * @author Markus Öhler * @param boolean $onlyPublished * @param boolean $noLimit True if no record count limit is used, false otherwise * @return object List of shopper group objects */ function getShopperGroups($onlyPublished=false, $noLimit = false) { $db = JFactory::getDBO(); $query = 'SELECT * FROM `#__virtuemart_shoppergroups` ORDER BY `virtuemart_vendor_id`,`shopper_group_name` '; if ($noLimit) { $this->_data = $this->_getList($query); } else { $this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit')); } return $this->_data; } function store(&$data){ $myfields = array('basePrice','variantModification','basePriceVariant', 'basePriceWithTax','basePriceWithTax','discountedPriceWithoutTax', 'salesPrice','priceWithoutTax', 'salesPriceWithDiscount','discountAmount','taxAmount','unitPrice'); $param ='show_prices='.$data['show_prices']."\n"; foreach($myfields as $fields){ $param .= $fields.'='.$data[$fields]."\n"; //attention there must be doublequotes $param .= $fields.'Text='.$data[$fields.'Text']."\n"; $param .= $fields.'Rounding='.$data[$fields.'Rounding']."\n"; } if(!class_exists('JParameter')) require(JPATH_VM_LIBRARIES.DS.'joomla'.DS.'html'.DS.'parameter.php' ); $jparam = new JParameter($param); $data['price_display'] = serialize(new JParameter($param)); return parent::store($data); } function makeDefault($id,$kind = 1) { //Prevent making anonymous Shoppergroup as default $adId = $this->getDefault(1); $anonymous_sg_id = $adId->virtuemart_shoppergroup_id; if($adId == $id){ $group = $this->getShoppergroupById($id); vmError(JText::sprintf('COM_VIRTUEMART_SHOPPERGROUP_CANT_MAKE_DEFAULT',$group->shopper_group_name,$id)); return false; } $this->_db->setQuery('UPDATE `#__virtuemart_shoppergroups` SET `default` = 0 WHERE `default`<"2"'); if (!$this->_db->query()) return ; $this->_db->setQuery('UPDATE `#__virtuemart_shoppergroups` SET `default` = "'.$kind.'" WHERE virtuemart_shoppergroup_id='.(int)$id); if (!$this->_db->query()) return ; return true; } /** * * Get default shoppergroup for anonymous and non anonymous * @param unknown_type $kind */ function getDefault($kind = 1, $onlyPublished = FALSE, $vendorId = 1){ $kind = $kind + 1; $q = 'SELECT * FROM `#__virtuemart_shoppergroups` WHERE `default` = "'.$kind.'" AND (`virtuemart_vendor_id` = "'.$vendorId.'" OR `shared` = "1") '; if($onlyPublished){ $q .= ' AND `published`="1" '; } $this->_db->setQuery($q); if(!$res = $this->_db->loadObject()){ $app = JFactory::getApplication(); $app->enqueueMessage('Attention no standard shopper group set '.$this->_db->getErrorMsg()); } else { //vmdebug('getDefault', $res); return $res; } } function appendShopperGroups(&$shopperGroups,$user,$onlyPublished = FALSE,$vendorId=1,$keepDefault = false){ $this->mergeSessionSgrps($shopperGroups); if(count($shopperGroups)<1 or $keepDefault){ $_defaultShopperGroup = $this->getDefault($user->guest,$onlyPublished,$vendorId); if(!in_array($_defaultShopperGroup->virtuemart_shoppergroup_id,$shopperGroups)){ $shopperGroups[] = $_defaultShopperGroup->virtuemart_shoppergroup_id; } } $this->removeSessionSgrps($shopperGroups); } function mergeSessionSgrps(&$ids){ $session = JFactory::getSession(); $shoppergroup_ids = $session->get('vm_shoppergroups_add',array(),'vm'); $ids = array_merge($ids,(array)$shoppergroup_ids); $ids = array_unique($ids); //$session->set('vm_shoppergroups_add',array(),'vm'); //vmdebug('mergeSessionSgrps',$shoppergroup_ids,$ids); } function removeSessionSgrps(&$ids){ $session = JFactory::getSession(); $shoppergroup_ids_remove = $session->get('vm_shoppergroups_remove',0,'vm'); if($shoppergroup_ids_remove!==0){ if(!is_array($shoppergroup_ids_remove)){ $shoppergroup_ids_remove = (array) $shoppergroup_ids_remove; } foreach($shoppergroup_ids_remove as $k => $id){ if(in_array($id,$ids)){ $key=array_search($id, $ids); if($key!==FALSE){ unset($ids[$key]); vmdebug('Anonymous case, remove session shoppergroup by plugin '.$id); } } } //$session->set('vm_shoppergroups_remove',0,'vm'); } } function remove($ids){ jimport( 'joomla.utilities.arrayhelper' ); JArrayHelper::toInteger($ids); $table = $this->getTable($this->_maintablename); $defaultSgId = $this->getDefault(0); $anonymSgId = $this->getDefault(1); foreach($ids as $id){ //Test if shoppergroup is default if($id == $defaultSgId->virtuemart_shoppergroup_id){ $this->_db->setQuery('SELECT shopper_group_name FROM `#__virtuemart_shoppergroups` WHERE `virtuemart_shoppergroup_id` = "'.(int)$id.'"'); $name = $this->_db->loadResult(); vmError(JText::sprintf('COM_VIRTUEMART_SHOPPERGROUP_DELETE_CANT_DEFAULT',vmText::_($name),$id)); continue; } //Test if shoppergroup is default if($id == $anonymSgId->virtuemart_shoppergroup_id){ $this->_db->setQuery('SELECT shopper_group_name FROM `#__virtuemart_shoppergroups` WHERE `virtuemart_shoppergroup_id` = "'.(int)$id.'"'); $name = $this->_db->loadResult(); vmError(JText::sprintf('COM_VIRTUEMART_SHOPPERGROUP_DELETE_CANT_DEFAULT',vmText::_($name),$id)); continue; } //Test if shoppergroup has members $this->_db->setQuery('SELECT * FROM `#__virtuemart_vmuser_shoppergroups` WHERE `virtuemart_shoppergroup_id` = "'.(int)$id.'"'); if($this->_db->loadResult()){ $this->_db->setQuery('SELECT shopper_group_name FROM `#__virtuemart_shoppergroups` WHERE `virtuemart_shoppergroup_id` = "'.(int)$id.'"'); $name = $this->_db->loadResult(); vmError(JText::sprintf('COM_VIRTUEMART_SHOPPERGROUP_DELETE_CANT_WITH_MEMBERS',vmText::_($name),$id)); continue; } if (!$table->delete($id)) { vmError(get_class( $this ).'::remove '.$table->getError()); return false; } } return true; } /** * Retrieves the Shopper Group Info of the SG specified by $id * * @param int $id * @param boolean $default_group * @return array */ static function getShoppergroupById($id, $default_group = false) { $virtuemart_vendor_id = 1; $db = JFactory::getDBO(); $q = 'SELECT `#__virtuemart_shoppergroups`.`virtuemart_shoppergroup_id`, `#__virtuemart_shoppergroups`.`shopper_group_name`, `default` AS default_shopper_group FROM `#__virtuemart_shoppergroups`'; if (!empty($id) && !$default_group) { $q .= ', `#__virtuemart_vmuser_shoppergroups`'; $q .= ' WHERE `#__virtuemart_vmuser_shoppergroups`.`virtuemart_user_id`="'.(int)$id.'" AND '; $q .= '`#__virtuemart_shoppergroups`.`virtuemart_shoppergroup_id`=`#__virtuemart_vmuser_shoppergroups`.`virtuemart_shoppergroup_id`'; } else { $q .= ' WHERE `#__virtuemart_shoppergroups`.`virtuemart_vendor_id`="'.(int)$virtuemart_vendor_id.'" AND `default`="2"'; } $db->setQuery($q); return $db->loadAssocList(); } } // pure php no closing tagproduct.php000066600000267330151372127700006761 0ustar00setMainTable ('products'); $this->starttime = microtime (TRUE); $this->maxScriptTime = VmConfig::getExecutionTime() * 0.95 - 1; $this->memory_limit = VmConfig::getMemoryLimit()-4; // $this->addvalidOrderingFieldName(array('m.mf_name','pp.product_price')); $app = JFactory::getApplication (); if ($app->isSite ()) { $this->_validOrderingFieldName = array(); $browseOrderByFields = VmConfig::get ('browse_orderby_fields',array('product_sku','category_name','mf_name','product_name')); } else { if (!class_exists ('shopFunctions')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'shopfunctions.php'); } $browseOrderByFields = ShopFunctions::getValidProductFilterArray (); $this->addvalidOrderingFieldName (array('product_price','product_sales')); //$this->addvalidOrderingFieldName (array('product_price')); // vmdebug('$browseOrderByFields',$browseOrderByFields); } $this->addvalidOrderingFieldName ((array)$browseOrderByFields); $this->removevalidOrderingFieldName ('virtuemart_product_id'); //$this->removevalidOrderingFieldName ('product_sales'); //unset($this->_validOrderingFieldName[0]);//virtuemart_product_id array_unshift ($this->_validOrderingFieldName, 'p.virtuemart_product_id'); $this->_selectedOrdering = VmConfig::get ('browse_orderby_field', '`p`.virtuemart_product_id'); $this->setToggleName('product_special'); $this->initialiseRequests (); //This is just done now for the moment for developing, the idea is of course todo this only when needed. $this->updateRequests (); } var $keyword = ""; var $product_parent_id = FALSE; var $virtuemart_manufacturer_id = FALSE; var $virtuemart_category_id = 0; var $search_type = ''; var $searchcustoms = FALSE; var $searchplugin = 0; var $filter_order = 'p.virtuemart_product_id'; var $filter_order_Dir = 'DESC'; var $valid_BE_search_fields = array('product_name', 'product_sku','product_gtin','product_mpn','`l`.`slug`', 'product_s_desc', '`l`.`metadesc`'); private $_autoOrder = 0; private $orderByString = 0; private $listing = FALSE; /** * This function resets the variables holding request depended data to the initial values * * @author Max Milbers */ function initialiseRequests () { $this->keyword = ""; $this->valid_search_fields = $this->valid_BE_search_fields; $this->product_parent_id = FALSE; $this->virtuemart_manufacturer_id = FALSE; $this->search_type = ''; $this->searchcustoms = FALSE; $this->searchplugin = 0; $this->filter_order = VmConfig::get ('browse_orderby_field'); ; $this->filter_order_Dir = VmConfig::get('prd_brws_orderby_dir', 'ASC'); $this->_uncategorizedChildren = null; } /** * This functions updates the variables of the model which are used in the sortSearchListQuery * with the variables from the Request * * @author Max Milbers */ function updateRequests () { $this->keyword = vRequest::uword ('keyword', "", ' ,-,+,.,_,#,/'); if ($this->keyword == "") { $this->keyword = vRequest::uword ('filter_product', "", ' ,-,+,.,_,#,/'); JRequest::setVar('filter_product',$this->keyword); JRequest::setVar('keyword',$this->keyword); } else { JRequest::setVar('keyword',$this->keyword); } $app = JFactory::getApplication (); $option = 'com_virtuemart'; $view = 'product'; if ($app->isSite ()) { $filter_order = JRequest::getString ('orderby', "0"); if($filter_order == "0"){ $filter_order_raw = $this->getLastProductOrdering($this->_selectedOrdering); $filter_order = $this->checkFilterOrder ($filter_order_raw); } else { vmdebug('my $filter_order ',$filter_order); $filter_order = $this->checkFilterOrder ($filter_order); vmdebug('my $filter_order after check',$filter_order); $this->setLastProductOrdering($filter_order); } $filter_order_Dir = strtoupper (JRequest::getWord ('dir', VmConfig::get('prd_brws_orderby_dir', 'ASC'))); $valid_search_fields = VmConfig::get ('browse_search_fields'); //vmdebug('$valid_search_fields ',$valid_search_fields); //unset($valid_search_fields[] } else { $filter_order = strtolower ($app->getUserStateFromRequest ('com_virtuemart.' . $view . '.filter_order', 'filter_order', $this->_selectedOrdering, 'cmd')); $filter_order = $this->checkFilterOrder ($filter_order); $filter_order_Dir = strtoupper ($app->getUserStateFromRequest ($option . '.' . $view . '.filter_order_Dir', 'filter_order_Dir', '', 'word')); $valid_search_fields = $this->valid_BE_search_fields; } $filter_order_Dir = $this->checkFilterDir ($filter_order_Dir); $this->filter_order = $filter_order; $this->filter_order_Dir = $filter_order_Dir; $this->valid_search_fields = $valid_search_fields; $this->product_parent_id = JRequest::getInt ('product_parent_id', FALSE); $this->virtuemart_manufacturer_id = JRequest::getInt ('virtuemart_manufacturer_id', FALSE); $this->search_type = JRequest::getVar ('search_type', ''); $this->searchcustoms = JRequest::getVar ('customfields', array(), 'default', 'array'); $this->searchplugin = JRequest::getInt ('custom_parent_id', 0); } /** * @author Max Milbers */ public function getLastProductOrdering($default = 0){ $session = JFactory::getSession(); return $session->get('vmlastproductordering', $default, 'vm'); } /** * @author Max Milbers */ public function setLastProductOrdering($ordering){ $session = JFactory::getSession(); return $session->set('vmlastproductordering', (string) $ordering, 'vm'); } /** * Sets the keyword variable for the search * * @param string $keyword */ function setKeyWord ($keyword) { $this->keyword = $keyword; } /** * New function for sorting, searching, filtering and pagination for product ids. * * @author Max Milbers */ function sortSearchListQuery ($onlyPublished = TRUE, $virtuemart_category_id = FALSE, $group = FALSE, $nbrReturnProducts = FALSE) { $app = JFactory::getApplication (); //User Q.Stanley said that removing group by is increasing the speed of product listing in a bigger shop (10k products) by factor 60 //So what was the reason for that we have it? TODO experiemental, find conditions for the need of group by $groupBy = ' group by p.`virtuemart_product_id` '; //administrative variables to organize the joining of tables $joinCategory = FALSE; $joinCatLang = false; $joinMf = FALSE; $joinMfLang = false; $joinPrice = FALSE; $joinCustom = FALSE; $joinShopper = FALSE; $joinChildren = FALSE; $joinLang = false; $orderBy = ' '; $where = array(); $useCore = TRUE; if ($this->searchplugin !== 0) { //reset generic filters ! Why? the plugin can do it, if it wishes it. // if ($this->keyword ==='') $where=array(); JPluginHelper::importPlugin ('vmcustom'); $dispatcher = JDispatcher::getInstance (); $PluginJoinTables = array(); $ret = $dispatcher->trigger ('plgVmAddToSearch', array(&$where, &$PluginJoinTables, $this->searchplugin)); foreach ($ret as $r) { if (!$r) { $useCore = FALSE; } } } if ($useCore) { $isSite = $app->isSite (); // if ( $this->keyword !== "0" and $group ===false) { if (!empty($this->keyword) and $this->keyword !== '' and $group === FALSE) { $keyword = '"%' .str_replace(array(' ','-'),'%',$this->_db->getEscaped( $this->keyword, true )). '%"'; //$keyword = '"%' . $this->_db->getEscaped ($this->keyword, TRUE) . '%"'; foreach ($this->valid_search_fields as $searchField) { if ($searchField == 'category_name' || $searchField == 'category_description') { //$joinCategory = TRUE; $joinCatLang = true; } else if ($searchField == 'mf_name') { //$joinMf = TRUE; $joinMfLang = true; } else if ($searchField == 'product_price') { $joinPrice = TRUE; } else if (!$joinLang and ($searchField == 'product_name' or $searchField == 'product_s_desc' or $searchField == 'product_desc' or $searchField == '`p`.product_sku' or $searchField == '`l`.slug') ){ $joinLang = TRUE; } if (strpos ($searchField, '`') !== FALSE){ $keywords_plural = preg_replace('/\s+/', '%" AND '.$searchField.' LIKE "%', $keyword); $filter_search[] = $searchField . ' LIKE ' . $keywords_plural; } else { $keywords_plural = preg_replace('/\s+/', '%" AND `'.$searchField.'` LIKE "%', $keyword); $filter_search[] = '`'.$searchField.'` LIKE '.$keywords_plural; //$filter_search[] = '`' . $searchField . '` LIKE ' . $keyword; } } if (!empty($filter_search)) { $where[] = '(' . implode (' OR ', $filter_search) . ')'; } else { $where[] = '`product_name` LIKE ' . $keyword; $joinLang = TRUE; //If they have no check boxes selected it will default to product name at least. } } // vmdebug('my $this->searchcustoms ',$this->searchcustoms); if (!empty($this->searchcustoms)) { $joinCustom = TRUE; foreach ($this->searchcustoms as $key => $searchcustom) { $custom_search[] = '(pf.`virtuemart_custom_id`="' . (int)$key . '" and pf.`custom_value` like "%' . $this->_db->getEscaped ($searchcustom, TRUE) . '%")'; } $where[] = " ( " . implode (' OR ', $custom_search) . " ) "; } if ($onlyPublished) { $where[] = ' p.`published`="1" '; } if($isSite and !VmConfig::get('use_as_catalog',0)) { if (VmConfig::get('stockhandle','none')=='disableit_children') { $where[] = ' ((p.`product_in_stock` - p.`product_ordered`) >"0" OR (children.`product_in_stock` - children.`product_ordered`) > "0") '; $joinChildren = TRUE; } else if (VmConfig::get('stockhandle','none')=='disableit') { $where[] = ' p.`product_in_stock` - p.`product_ordered` >"0" '; } } if ($virtuemart_category_id > 0) { $joinCategory = TRUE; $where[] = ' `pc`.`virtuemart_category_id` = ' . $virtuemart_category_id; } else if ($isSite and !VmConfig::get('show_uncat_child_products',TRUE)) { $joinCategory = TRUE; $where[] = ' `pc`.`virtuemart_category_id` > 0 '; } if ($this->product_parent_id) { $where[] = ' p.`product_parent_id` = ' . $this->product_parent_id; } if ($isSite) { $usermodel = VmModel::getModel ('user'); $currentVMuser = $usermodel->getUser (); $virtuemart_shoppergroup_ids = (array)$currentVMuser->shopper_groups; if (is_array ($virtuemart_shoppergroup_ids)) { $sgrgroups = array(); foreach ($virtuemart_shoppergroup_ids as $key => $virtuemart_shoppergroup_id) { $sgrgroups[] = ' `ps`.`virtuemart_shoppergroup_id`= "' . (int)$virtuemart_shoppergroup_id . '" '; } $sgrgroups[] = ' `ps`.`virtuemart_shoppergroup_id` IS NULL '; $where[] = " ( " . implode (' OR ', $sgrgroups) . " ) "; $joinShopper = TRUE; } } if ($this->virtuemart_manufacturer_id) { $joinMf = TRUE; $where[] = ' `#__virtuemart_product_manufacturers`.`virtuemart_manufacturer_id` = ' . $this->virtuemart_manufacturer_id; } // Time filter if ($this->search_type != '') { $search_order = $this->_db->getEscaped (JRequest::getWord ('search_order') == 'bf' ? '<' : '>'); switch ($this->search_type) { case 'parent': $where[] = 'p.`product_parent_id` = "0"'; break; case 'product': $where[] = 'p.`modified_on` ' . $search_order . ' "' . $this->_db->getEscaped (JRequest::getVar ('search_date')) . '"'; break; case 'price': $joinPrice = TRUE; $where[] = 'pp.`modified_on` ' . $search_order . ' "' . $this->_db->getEscaped (JRequest::getVar ('search_date')) . '"'; break; case 'withoutprice': $joinPrice = TRUE; $where[] = 'pp.`product_price` IS NULL'; break; case 'stockout': $where[] = ' p.`product_in_stock`- p.`product_ordered` < 1'; break; case 'stocklow': $where[] = 'p.`product_in_stock`- p.`product_ordered` < p.`low_stock_notification`'; break; } } // special orders case //vmdebug('my filter ordering ',$this->filter_order); $ff_select_price = ''; switch ($this->filter_order) { case '`p`.product_special': if($isSite){ $where[] = ' p.`product_special`="1" '; // TODO Change to a individual button $orderBy = 'ORDER BY RAND()'; } else { $orderBy = 'ORDER BY p.`product_special`'; } break; case 'category_name': $orderBy = ' ORDER BY `category_name` '; $joinCategory = TRUE; $joinCatLang = true; break; case 'category_description': $orderBy = ' ORDER BY `category_description` '; $joinCategory = TRUE; $joinCatLang = true; break; case 'mf_name': $orderBy = ' ORDER BY `mf_name` '; $joinMf = TRUE; $joinMfLang = true; break; case 'pc.ordering': $orderBy = ' ORDER BY `pc`.`ordering` '; $joinCategory = TRUE; break; case 'product_price': //$filters[] = 'p.`virtuemart_product_id` = p.`virtuemart_product_id`'; //$orderBy = ' ORDER BY `product_price` '; //$orderBy = ' ORDER BY `ff_final_price`, `product_price` '; $orderBy = ' ORDER BY `product_price` '; $ff_select_price = ' , IF(pp.override, pp.product_override_price, pp.product_price) as product_price '; $joinPrice = TRUE; break; case '`p`.created_on': $orderBy = ' ORDER BY p.`created_on` '; break; default; if (!empty($this->filter_order)) { $orderBy = ' ORDER BY ' . $this->filter_order . ' '; } else { $this->filter_order_Dir = ''; } break; } //Group case from the modules if ($group) { $latest_products_days = VmConfig::get ('latest_products_days', 7); $latest_products_orderBy = VmConfig::get ('latest_products_orderBy','created_on'); $groupBy = 'group by p.`virtuemart_product_id` '; switch ($group) { case 'featured': $where[] = 'p.`product_special`="1" '; $orderBy = 'ORDER BY RAND() '; break; case 'latest': $date = JFactory::getDate (time () - (60 * 60 * 24 * $latest_products_days)); $dateSql = $date->toMySQL (); //$where[] = 'p.`' . $latest_products_orderBy . '` > "' . $dateSql . '" '; $orderBy = 'ORDER BY p.`' . $latest_products_orderBy . '`'; $this->filter_order_Dir = 'DESC'; break; case 'random': $orderBy = ' ORDER BY RAND() '; //LIMIT 0, '.(int)$nbrReturnProducts ; //TODO set limit LIMIT 0, '.(int)$nbrReturnProducts; break; case 'topten': $orderBy = ' ORDER BY p.`product_sales` '; //LIMIT 0, '.(int)$nbrReturnProducts; //TODO set limitLIMIT 0, '.(int)$nbrReturnProducts; $joinPrice = true; $where[] = 'pp.`product_price`>"0.0" '; $this->filter_order_Dir = 'DESC'; break; case 'recent': $rSession = JFactory::getSession(); $rIds = $rSession->get('vmlastvisitedproductids', array(), 'vm'); // get recent viewed from browser session return $rIds; } $this->searchplugin = FALSE; } } $joinedTables = array(); //This option switches between showing products without the selected language or only products with language. if($app->isSite() and !VmConfig::get('prodOnlyWLang',true)){ //Maybe we have to join the language to order by product name, description, etc,... if(!$joinLang){ $productLangFields = array('product_s_desc','product_desc','product_name','metadesc','metakey','slug'); foreach($productLangFields as $field){ if(strpos($orderBy,$field,6)!==FALSE){ $joinLang = true; break; } } } } else { $joinLang = true; } $select = ' p.`virtuemart_product_id`'.$ff_select_price.' FROM `#__virtuemart_products` as p '; if ($joinLang) { $joinedTables[] = ' INNER JOIN `#__virtuemart_products_' . VmConfig::$vmlang . '` as l using (`virtuemart_product_id`)'; } if ($joinShopper == TRUE) { $joinedTables[] = ' LEFT JOIN `#__virtuemart_product_shoppergroups` as ps ON p.`virtuemart_product_id` = `ps`.`virtuemart_product_id` '; //$joinedTables[] = ' LEFT OUTER JOIN `#__virtuemart_shoppergroups` as s ON s.`virtuemart_shoppergroup_id` = `#__virtuemart_product_shoppergroups`.`virtuemart_shoppergroup_id` '; } if ($joinCategory == TRUE or $joinCatLang) { $joinedTables[] = ' LEFT JOIN `#__virtuemart_product_categories` as pc ON p.`virtuemart_product_id` = `pc`.`virtuemart_product_id` '; if($joinCatLang){ $joinedTables[] = ' LEFT JOIN `#__virtuemart_categories_' . VMLANG . '` as c ON c.`virtuemart_category_id` = `pc`.`virtuemart_category_id`'; } } if ($joinMf == TRUE or $joinMfLang) { $joinedTables[] = ' LEFT JOIN `#__virtuemart_product_manufacturers` ON p.`virtuemart_product_id` = `#__virtuemart_product_manufacturers`.`virtuemart_product_id` '; if($joinMfLang){ $joinedTables[] = 'LEFT JOIN `#__virtuemart_manufacturers_' . VMLANG . '` as m ON m.`virtuemart_manufacturer_id` = `#__virtuemart_product_manufacturers`.`virtuemart_manufacturer_id` '; } } if ($joinPrice == TRUE) { $joinedTables[] = ' LEFT JOIN `#__virtuemart_product_prices` as pp ON p.`virtuemart_product_id` = pp.`virtuemart_product_id` '; } if ($this->searchcustoms) { $joinedTables[] = ' LEFT JOIN `#__virtuemart_product_customfields` as pf ON p.`virtuemart_product_id` = pf.`virtuemart_product_id` '; } if ($this->searchplugin !== 0) { if (!empty($PluginJoinTables)) { $plgName = $PluginJoinTables[0]; $joinedTables[] = ' LEFT JOIN `#__virtuemart_product_custom_plg_' . $plgName . '` as ' . $plgName . ' ON ' . $plgName . '.`virtuemart_product_id` = p.`virtuemart_product_id` '; } } if ($joinChildren) { $joinedTables[] = ' LEFT OUTER JOIN `#__virtuemart_products` children ON p.`virtuemart_product_id` = children.`product_parent_id` '; } if (count ($where) > 0) { $whereString = ' WHERE (' . implode ("\n AND ", $where) . ') '; } else { $whereString = ''; } //vmdebug ( $joinedTables.' joined ? ',$select, $joinedTables, $whereString, $groupBy, $orderBy, $this->filter_order_Dir ); /* jexit(); */ $this->orderByString = $orderBy; if($this->_onlyQuery){ return (array($select,$joinedTables,$where,$orderBy,$joinLang)); } $joinedTables = " \n".implode(" \n",$joinedTables); $product_ids = $this->exeSortSearchListQuery (2, $select, $joinedTables, $whereString, $groupBy, $orderBy, $this->filter_order_Dir, $nbrReturnProducts); return $product_ids; } /** * Override * * @see VmModel::setPaginationLimits() */ public function setPaginationLimits () { $app = JFactory::getApplication (); $view = JRequest::getWord ('view','virtuemart'); $cateid = JRequest::getInt ('virtuemart_category_id', -1); $manid = JRequest::getInt ('virtuemart_manufacturer_id', 0); $limitString = 'com_virtuemart.' . $view . 'c' . $cateid . '.limit'; $limit = (int)$app->getUserStateFromRequest ($limitString, 'limit'); $limitStartString = 'com_virtuemart.' . $view . '.limitstart'; if ($app->isSite () and ($cateid != -1 or $manid != 0) ) { $lastCatId = ShopFunctionsF::getLastVisitedCategoryId (); $lastManId = ShopFunctionsF::getLastVisitedManuId (); vmdebug('setPaginationLimits is site and $cateid,$manid ',$cateid,$lastCatId,$manid); if( !empty($cateid) and $cateid != -1) { $gCatId = $cateid; } else if( !empty($lastCatId) ) { $gCatId = $lastCatId; } if(!empty($gCatId)){ $catModel= VmModel::getModel('category'); $category = $catModel->getCategory($gCatId); } else { $category = new stdClass(); } if ((!empty($lastCatId) and $lastCatId != $cateid) or (!empty($manid) and $lastManId != $manid)) { //We are in a new category or another manufacturer, so we start at page 1 $limitStart = JRequest::getInt ('limitstart', 0); } else { //We were already in the category/manufacturer, so we take the value stored in the session $limitStartString = 'com_virtuemart.' . $view . 'c' . $cateid .'m'.$manid. '.limitstart'; $limitStart = $app->getUserStateFromRequest ($limitStartString, 'limitstart', JRequest::getInt ('limitstart', 0), 'int'); } if(empty($limit) and !empty($category->limit_list_initial)){ $suglimit = $category->limit_list_initial; } else if(!empty($limit)){ $suglimit = $limit; } else { $suglimit = VmConfig::get ('llimit_init_FE', 20); } if(empty($category->products_per_row)){ $category->products_per_row = VmConfig::get ('products_per_row', 3); } $rest = $suglimit%$category->products_per_row; $limit = $suglimit - $rest; if(!empty($category->limit_list_step)){ $prod_per_page = explode(",",$category->limit_list_step); } else { //fix by hjet $prod_per_page = explode(",",VmConfig::get('pagseq_'.$category->products_per_row)); } if($limit <= $prod_per_page['0'] && array_key_exists('0',$prod_per_page)){ $limit = $prod_per_page['0']; } //vmdebug('Calculated $limit ',$limit,$suglimit); } else { $limitStart = $app->getUserStateFromRequest ('com_virtuemart.' . $view . '.limitstart', 'limitstart', JRequest::getInt ('limitstart', 0), 'int'); } if(empty($limit)){ if($app->isSite()){ $limit = VmConfig::get ('llimit_init_FE'); } else { $limit = VmConfig::get ('llimit_init_BE'); } if(empty($limit)){ $limit = 30; } } $this->setState ('limit', $limit); $this->setState ($limitString, $limit); $this->_limit = $limit; //There is a strange error in the frontend giving back 9 instead of 10, or 24 instead of 25 //This functions assures that the steps of limitstart fit with the limit $limitStart = ceil ((float)$limitStart / (float)$limit) * $limit; $this->setState ('limitstart', $limitStart); $this->setState ($limitStartString, $limitStart); $this->_limitStart = $limitStart; return array($this->_limitStart, $this->_limit); } /** * This function creates a product with the attributes of the parent. * * @param int $virtuemart_product_id * @param boolean $front for frontend use * @param boolean $withCalc calculate prices? * @param boolean published * @param int quantity * @param boolean load customfields */ public function getProduct ($virtuemart_product_id = NULL, $front = TRUE, $withCalc = TRUE, $onlyPublished = TRUE, $quantity = 1,$customfields = TRUE,$virtuemart_shoppergroup_ids=0) { if (isset($virtuemart_product_id)) { $virtuemart_product_id = $this->setId ($virtuemart_product_id); } else { if (empty($this->_id)) { vmError('Can not return product with empty id'); return FALSE; } else { $virtuemart_product_id = $this->_id; } } if($virtuemart_shoppergroup_ids !=0 and is_array($virtuemart_shoppergroup_ids)){ $virtuemart_shoppergroup_idsString = implode('',$virtuemart_shoppergroup_ids); } else { $virtuemart_shoppergroup_idsString = $virtuemart_shoppergroup_ids; } $front = $front?TRUE:0; $withCalc = $withCalc?TRUE:0; $onlyPublished = $onlyPublished?TRUE:0; $customfields = $customfields?TRUE:0; $this->withRating = $this->withRating?TRUE:0; $productKey = $virtuemart_product_id.$front.$onlyPublished.$quantity.$virtuemart_shoppergroup_idsString.$withCalc.$customfields.$this->withRating; static $_products = array(); // vmdebug('$productKey, not from cache : '.$productKey); if (array_key_exists ($productKey, $_products)) { //vmdebug('getProduct, take from cache : '.$productKey); return $_products[$productKey]; } else if(!$customfields or !$withCalc){ $productKeyTmp = $virtuemart_product_id.$front.$onlyPublished.$quantity.$virtuemart_shoppergroup_idsString.TRUE.TRUE.TRUE; if (array_key_exists ($productKeyTmp, $_products)) { //vmdebug('getProduct, take from cache full product '.$productKeyTmp); return $_products[$productKeyTmp]; } } if ($this->memory_limit<$mem = round(memory_get_usage(FALSE)/(1024*1024),2)) { vmdebug ('Memory limit reached in model product getProduct('.$virtuemart_product_id.'), $customfields= '.$customfields.' consumed: '.$mem.'M'); vmError ('Memory limit '.$this->memory_limit.' reached in model product getProduct() ' . $virtuemart_product_id. ' tried to allocate '.$mem); return false; } $child = $this->getProductSingle ($virtuemart_product_id, $front,$quantity,$customfields,$virtuemart_shoppergroup_ids); if (!$child->published && $onlyPublished) { //vmdebug('getProduct child is not published, returning zero'); $_products[$productKey] = FALSE; return FALSE; } if(!isset($child->orderable)){ $child->orderable = TRUE; } //store the original parent id $pId = $child->virtuemart_product_id; $ppId = $child->product_parent_id; $published = $child->published; $i = 0; $runtime = microtime (TRUE) - $this->starttime; //Check for all attributes to inherited by parent products while (!empty($child->product_parent_id)) { $runtime = microtime (TRUE) - $this->starttime; if ($runtime >= $this->maxScriptTime) { vmdebug ('Max execution time reached in model product getProduct() ', $child); vmError ('Max execution time reached in model product getProduct() ' . $child->product_parent_id); break; } else { if ($i > 10) { vmdebug ('Time: ' . $runtime . ' Too many child products in getProduct() ', $child); vmError ('Time: ' . $runtime . ' Too many child products in getProduct() ' . $child->product_parent_id); break; } } $parentProduct = $this->getProductSingle ($child->product_parent_id, $front,$quantity,$customfields,$virtuemart_shoppergroup_ids); if ($child->product_parent_id === $parentProduct->product_parent_id) { vmError('Error, parent product with virtuemart_product_id = '.$parentProduct->virtuemart_product_id.' has same parent id like the child with virtuemart_product_id '.$child->virtuemart_product_id); break; } $attribs = get_object_vars ($parentProduct); foreach ($attribs as $k=> $v) { if ('product_in_stock' != $k and 'product_ordered' != $k) {// Do not copy parent stock into child if (strpos ($k, '_') !== 0 and empty($child->$k)) { $child->$k = $v; // vmdebug($child->product_parent_id.' $child->$k',$child->$k); } } } $i++; if ($child->product_parent_id != $parentProduct->product_parent_id) { $child->product_parent_id = $parentProduct->product_parent_id; } else { $child->product_parent_id = 0; } } //vmdebug('getProduct Time: '.$runtime); $child->published = $published; $child->virtuemart_product_id = $pId; $child->product_parent_id = $ppId; if ($withCalc) { $child->prices = $this->getPrice ($child, array(), 1); //vmdebug(' use of $child->prices = $this->getPrice($child,array(),1)'); } if (empty($child->product_template)) { $child->product_template = VmConfig::get ('producttemplate'); } if(!empty($child->canonCatLink)) { // Add the product link for canonical $child->canonical = 'index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=' . $virtuemart_product_id . '&virtuemart_category_id=' . $child->canonCatLink; } else { $child->canonical = 'index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=' . $virtuemart_product_id; } $child->canonical = JRoute::_ ($child->canonical,FALSE); if(!empty($child->virtuemart_category_id)) { $child->link = JRoute::_ ('index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=' . $virtuemart_product_id . '&virtuemart_category_id=' . $child->virtuemart_category_id, FALSE); } else { $child->link = $child->canonical; } $child->quantity = $quantity; $app = JFactory::getApplication (); if ($app->isSite () and VmConfig::get ('stockhandle', 'none') == 'disableit' and ($child->product_in_stock - $child->product_ordered) <= 0) { vmdebug ('STOCK 0', VmConfig::get ('use_as_catalog', 0), VmConfig::get ('stockhandle', 'none'), $child->product_in_stock); $_products[$productKey] = FALSE; } else { $_products[$productKey] = $child; } return $_products[$productKey]; } public function loadProductPrices($productId,$quantity,$virtuemart_shoppergroup_ids,$front){ $db = JFactory::getDbo(); $this->_nullDate = $db->getNullDate(); $jnow = JFactory::getDate(); $this->_now = $jnow->toMySQL(); //$productId = $this->_id===0? $product->virtuemart_product_id:$this->_id; //$productId = $product->virtuemart_product_id===0? $this->_id:$product->virtuemart_product_id; $q = 'SELECT * FROM `#__virtuemart_product_prices` WHERE `virtuemart_product_id` = "'.$productId.'" '; if($front){ if(count($virtuemart_shoppergroup_ids)>0){ $q .= ' AND ('; $sqrpss = ''; foreach($virtuemart_shoppergroup_ids as $sgrpId){ $sqrpss .= ' `virtuemart_shoppergroup_id` ="'.$sgrpId.'" OR '; } $q .= substr($sqrpss,0,-4); $q .= ' OR `virtuemart_shoppergroup_id` IS NULL OR `virtuemart_shoppergroup_id`="0") '; } $q .= ' AND ( (`product_price_publish_up` IS NULL OR `product_price_publish_up` = "' . $db->getEscaped($this->_nullDate) . '" OR `product_price_publish_up` <= "' .$db->getEscaped($this->_now) . '" ) AND (`product_price_publish_down` IS NULL OR `product_price_publish_down` = "' .$db->getEscaped($this->_nullDate) . '" OR product_price_publish_down >= "' . $db->getEscaped($this->_now) . '" ) )'; $quantity = (int)$quantity; if(!empty($quantity)){ $q .= ' AND( (`price_quantity_start` IS NULL OR `price_quantity_start`="0" OR `price_quantity_start` <= '.$quantity.') AND (`price_quantity_end` IS NULL OR `price_quantity_end`="0" OR `price_quantity_end` >= '.$quantity.') )'; } } else { $q .= ' ORDER BY `product_price` DESC'; } $db->setQuery($q); $prices = $db->loadAssocList(); $err = $db->getErrorMsg(); if(!empty($err)){ vmError('getProductSingle '.$err); } else { if($prices and count($prices)==0){ vmdebug('getProductSingle getPrice query',$q); } } return $prices; } public function getProductPrices(&$product,$quantity,$virtuemart_shoppergroup_ids,$front,$loop=false){ $product->product_price = null; $product->product_override_price = null; $product->override = null; $product->virtuemart_product_price_id = null; $product->virtuemart_shoppergroup_id = null; $product->product_price_publish_up = null; $product->product_price_publish_down = null; $product->price_quantity_start = null; $product->price_quantity_end = null; $productId = $product->virtuemart_product_id===0? $this->_id:$product->virtuemart_product_id; $product->prices = $this->loadProductPrices($productId,$quantity,$virtuemart_shoppergroup_ids,$front); $i = 0; $runtime = microtime (TRUE) - $this->starttime; $product_parent_id = $product->product_parent_id; //Check for all attributes to inherited by parent products if($loop) { while ( $product_parent_id and count($product->prices)==0) { $runtime = microtime (TRUE) - $this->starttime; if ($runtime >= $this->maxScriptTime) { vmdebug ('Max execution time reached in model product getProductPrices() ', $product); vmError ('Max execution time reached in model product getProductPrices() ' . $product->product_parent_id); break; } else { if ($i > 10) { vmdebug ('Time: ' . $runtime . ' Too many child products in getProductPrices() ', $product); vmError ('Time: ' . $runtime . ' Too many child products in getProductPrices() ' . $product->product_parent_id); break; } } $product->prices = $this->loadProductPrices($product_parent_id,$quantity,$virtuemart_shoppergroup_ids,$front); $i++; if(!isset($product->prices['salesPrice']) and $product->product_parent_id!=0){ $db = JFactory::getDbo(); $db->setQuery (' SELECT `product_parent_id` FROM `#__virtuemart_products` WHERE `virtuemart_product_id` =' . $product_parent_id); $product_parent_id = $db->loadResult (); } } } if(count($product->prices)===1){ unset($product->prices[0]['virtuemart_product_id']); unset($product->prices[0]['created_on']); unset($product->prices[0]['created_by']); unset($product->prices[0]['modified_on']); unset($product->prices[0]['modified_by']); unset($product->prices[0]['locked_on']); unset($product->prices[0]['locked_by']); //vmdebug('getProductPrices my price ',$product->prices[0]); // For merging of the price and product array, the shoppergroup id from price must be unsetted. // Otherwise the product becomes the shoppergroup from the price. $priceShoppergroupID = $product->prices[0]['virtuemart_shoppergroup_id']; unset($product->prices[0]['virtuemart_shoppergroup_id']); $product = (object)array_merge ((array)$product, (array)$product->prices[0]); $product->prices[0]['virtuemart_shoppergroup_id'] = $priceShoppergroupID; } else if ( $front and count($product->prices)>1 ) { foreach($product->prices as $price){ if(empty($price['virtuemart_shoppergroup_id'])){ if(empty($emptySpgrpPrice))$emptySpgrpPrice = $price; } else if(in_array($price['virtuemart_shoppergroup_id'],$virtuemart_shoppergroup_ids)){ $spgrpPrice = $price; break; } } if(!empty($spgrpPrice)){ $product = (object)array_merge ((array)$product, (array)$spgrpPrice); //$prices = (array)$spgrpPrice; } else if(!empty($emptySpgrpPrice)){ $product = (object)array_merge ((array)$product, (array)$emptySpgrpPrice); //$prices = (array)$emptySpgrpPrice; } else { vmWarn('COM_VIRTUEMART_PRICE_AMBIGUOUS'); $product = (object)array_merge ((array)$product, (array)$product->prices[0]); //$prices = (array)$product->prices[0]; } } } var $withRating = false; public function getProductSingle ($virtuemart_product_id = NULL, $front = TRUE, $quantity = 1,$customfields=TRUE,$virtuemart_shoppergroup_ids=0) { //$this->fillVoidProduct($front); if (!empty($virtuemart_product_id)) { $virtuemart_product_id = $this->setId ($virtuemart_product_id); } if($virtuemart_shoppergroup_ids===0){ $usermodel = VmModel::getModel ('user'); $currentVMuser = $usermodel->getCurrentUser (); if(!is_array($currentVMuser->shopper_groups)){ $virtuemart_shoppergroup_ids = (array)$currentVMuser->shopper_groups; } else { $virtuemart_shoppergroup_ids = $currentVMuser->shopper_groups; } } $virtuemart_shoppergroup_idsString = 0; if(!empty($virtuemart_shoppergroup_ids) and is_array($virtuemart_shoppergroup_ids)){ $virtuemart_shoppergroup_idsString = implode('',$virtuemart_shoppergroup_ids); } else if(!empty($virtuemart_shoppergroup_ids)){ $virtuemart_shoppergroup_idsString = $virtuemart_shoppergroup_ids; } $front = $front?TRUE:0; $customfields = $customfields?TRUE:0; $this->withRating = $this->withRating?TRUE:0; $productKey = $virtuemart_product_id.$virtuemart_shoppergroup_idsString.$quantity.$front.$customfields.$this->withRating; //$productKey = md5($virtuemart_product_id.$front.$quantity.$customfields.$this->withRating.$virtuemart_shoppergroup_idsString); static $_productsSingle = array(); if (array_key_exists ($productKey, $_productsSingle)) { //vmdebug('getProduct, take from cache '.$productKey); return $_productsSingle[$productKey]; } else if(!$customfields or !$this->withRating){ $productKey = $virtuemart_product_id.$virtuemart_shoppergroup_idsString.$quantity.TRUE.TRUE.$this->withRating; //vmdebug('getProductSingle, recreate $productKey '.$productKey); if (array_key_exists ($productKey, $_productsSingle)) { //vmdebug('getProductSingle, take from cache recreated key',$_productsSingle[$productKey]); return $_productsSingle[$productKey]; } } if (!empty($this->_id)) { // $joinIds = array('virtuemart_product_price_id' =>'#__virtuemart_product_prices','virtuemart_manufacturer_id' =>'#__virtuemart_product_manufacturers','virtuemart_customfield_id' =>'#__virtuemart_product_customfields'); if($this->withRating){ $joinIds = array('rating' => '#__virtuemart_ratings','virtuemart_manufacturer_id' => '#__virtuemart_product_manufacturers', 'virtuemart_customfield_id' => '#__virtuemart_product_customfields'); } else { $joinIds = array('virtuemart_manufacturer_id' => '#__virtuemart_product_manufacturers', 'virtuemart_customfield_id' => '#__virtuemart_product_customfields'); } $product = $this->getTable ('products'); $product->load ($this->_id, 0, 0, $joinIds); $xrefTable = $this->getTable ('product_medias'); $product->virtuemart_media_id = $xrefTable->load ((int)$this->_id); // Load the shoppers the product is available to for Custom Shopper Visibility $product->shoppergroups = $this->getProductShoppergroups ($this->_id); if (!empty($product->shoppergroups) and $front) { if (!class_exists ('VirtueMartModelUser')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'user.php'); } $commonShpgrps = array_intersect ($virtuemart_shoppergroup_ids, $product->shoppergroups); if (empty($commonShpgrps)) { vmdebug('getProductSingle creating void product, usergroup does not fit ',$product->shoppergroups); return $this->fillVoidProduct ($front); } } $this->getProductPrices($product,$quantity,$virtuemart_shoppergroup_ids,$front); if (!empty($product->virtuemart_manufacturer_id)) { $mfTable = $this->getTable ('manufacturers'); $mfTable->load ((int)$product->virtuemart_manufacturer_id); $product = (object)array_merge ((array)$mfTable, (array)$product); } else { $product->virtuemart_manufacturer_id = array(); $product->mf_name = ''; $product->mf_desc = ''; $product->mf_url = ''; } // Load the categories the product is in //$product->categories = $this->getProductCategories ($this->_id, $front); $product->categories = $this->getProductCategories ($this->_id, FALSE); //We need also the unpublished categories, else the calculation rules do not work if(!empty($product->product_url)){ $product->canonCatLink = $product->product_url; } else if(!empty($product->categories)){ $categories = $this->getProductCategories ($this->_id, TRUE); //only published if($categories){ if(!is_array($categories)) $categories = (array)$categories; $product->canonCatLink = $categories[0]; } } $product->virtuemart_category_id = 0; if ($front) { if (!empty($product->categories) and is_array ($product->categories) and count($product->categories)>1){ if (!class_exists ('shopFunctionsF')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'shopfunctionsf.php'); } //We must first check if we come from another category, due the canoncial link we would have always the same catgory id for a product //But then we would have wrong neighbored products / category and product layouts $last_category_id = shopFunctionsF::getLastVisitedCategoryId (); if ($last_category_id!==0 and in_array ($last_category_id, $product->categories)) { $product->virtuemart_category_id = $last_category_id; //vmdebug('I take for product the last category ',$last_category_id,$product->categories); } else { $virtuemart_category_id = vRequest::getInt ('virtuemart_category_id', 0); if ($virtuemart_category_id!==0 and in_array ($virtuemart_category_id, $product->categories)) { $product->virtuemart_category_id = $virtuemart_category_id; //vmdebug('I take for product the requested category ',$virtuemart_category_id,$product->categories); } else { if (!empty($product->categories) and is_array ($product->categories) and array_key_exists (0, $product->categories)) { $product->virtuemart_category_id = $product->canonCatLink; //vmdebug('I take for product the main category ',$product->virtuemart_category_id,$product->categories); } } } } else if(!empty($product->canonCatLink)) { $product->virtuemart_category_id = $product->canonCatLink; } } else { //This construction should allow us to see category depended prices in the BE $virtuemart_category_id = JRequest::getInt ('virtuemart_category_id', 0); if($virtuemart_category_id!==0 and !empty($product->categories) ) { if(is_array($product->categories) and in_array ($virtuemart_category_id, $product->categories)){ $product->virtuemart_category_id = $virtuemart_category_id; } else if($product->categories==$virtuemart_category_id) { $product->virtuemart_category_id = $virtuemart_category_id; } } if (empty($product->virtuemart_category_id)) { if (!empty($product->categories) and is_array ($product->categories) and !empty($product->categories[0])) { $product->virtuemart_category_id = $product->categories[0]; } else { $product->virtuemart_category_id = null; } } // vmdebug('getProductSingle BE request $virtuemart_category_id',$virtuemart_category_id,$product->virtuemart_category_id); } if(!empty($product->virtuemart_category_id)){ $q = 'SELECT `ordering`,`id` FROM `#__virtuemart_product_categories` WHERE `virtuemart_product_id` = "' . $this->_id . '" and `virtuemart_category_id`= "' . $product->virtuemart_category_id . '" '; $this->_db->setQuery ($q); // change for faster ordering $ordering = $this->_db->loadObject (); if (!empty($ordering)) { $product->ordering = $ordering->ordering; //This is the ordering id in the list to store the ordering notice by Max Milbers $product->id = $ordering->id; } else { $product->ordering = $this->_autoOrder++; $product->id = $this->_autoOrder; vmdebug('$product->virtuemart_category_id no ordering stored for '.$ordering->id); } $catTable = $this->getTable ('categories'); $catTable->load ($product->virtuemart_category_id); $product->category_name = $catTable->category_name; } else { $product->category_name = null; $product->virtuemart_category_id = null; $product->ordering = null; $product->id = $this->_autoOrder++; vmdebug('$product->virtuemart_category_id is empty'); } if (!$front and $customfields) { if(!$this->listing){ $customfieldModel = VmModel::getModel ('Customfields'); $product->customfields = $customfieldModel->getproductCustomslist ($this->_id); if (empty($product->customfields) and !empty($product->product_parent_id)) { //$product->customfields = $this->productCustomsfieldsClone($product->product_parent_id,true) ; $product->customfields = $customfieldModel->getproductCustomslist ($product->product_parent_id, $this->_id); $product->customfields_fromParent = TRUE; } } } else if($customfields){ //only needed in FE productdetails, is now loaded in the view.html.php // /* Load the neighbours */ // $product->neighbours = $this->getNeighborProducts($product); // Fix the product packaging if ($product->product_packaging) { $product->packaging = $product->product_packaging & 0xFFFF; $product->box = ($product->product_packaging >> 16) & 0xFFFF; } else { $product->packaging = ''; $product->box = ''; } // set the custom variants //vmdebug('getProductSingle id '.$product->virtuemart_product_id.' $product->virtuemart_customfield_id '.$product->virtuemart_customfield_id); if (!empty($product->virtuemart_customfield_id)) { $customfieldModel = VmModel::getModel ('Customfields'); // Load the custom product fields $product->customfields = $customfieldModel->getProductCustomsField ($product); $product->customfieldsRelatedCategories = $customfieldModel->getProductCustomsFieldRelatedCategories ($product); $product->customfieldsRelatedProducts = $customfieldModel->getProductCustomsFieldRelatedProducts ($product); // custom product fields for add to cart $product->customfieldsCart = $customfieldModel->getProductCustomsFieldCart ($product); $child = $this->getProductChilds ($this->_id); $product->customsChilds = $customfieldModel->getProductCustomsChilds ($child, $this->_id); } // Check the stock level if (empty($product->product_in_stock)) { $product->product_in_stock = 0; } } $_productsSingle[$productKey] = $product; } else { $_productsSingle[$productKey] = $this->fillVoidProduct ($front); } $this->product = $_productsSingle[$productKey]; return $_productsSingle[$productKey]; } /** * This fills the empty properties of a product * todo add if(!empty statements * * @author Max Milbers * @param unknown_type $product * @param unknown_type $front */ private function fillVoidProduct ($front = TRUE) { /* Load an empty product */ $product = $this->getTable ('products'); $product->load (); /* Add optional fields */ $product->virtuemart_manufacturer_id = NULL; $product->virtuemart_product_price_id = NULL; if (!class_exists ('VirtueMartModelVendor')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php'); } //$product->virtuemart_vendor_id = VirtueMartModelVendor::getLoggedVendor(); $product->product_price = NULL; $product->product_currency = NULL; $product->product_price_quantity_start = NULL; $product->product_price_quantity_end = NULL; $product->product_price_publish_up = NULL; $product->product_price_publish_down = NULL; $product->product_tax_id = NULL; $product->product_discount_id = NULL; $product->product_override_price = NULL; $product->override = NULL; $product->categories = array(); $product->shoppergroups = array(); if ($front) { $product->link = ''; $product->prices = array(); $product->virtuemart_category_id = 0; $product->virtuemart_shoppergroup_id = 0; $product->mf_name = ''; $product->packaging = ''; $product->related = ''; $product->box = ''; } return $product; } /** * Load the product category * * @author Kohl Patrick,Max Milbers * @return array list of categories product is in */ public function getProductCategories ($virtuemart_product_id = 0, $front = FALSE) { $categories = array(); if ($virtuemart_product_id > 0) { $q = 'SELECT pc.`virtuemart_category_id` FROM `#__virtuemart_product_categories` as pc'; if ($front) { $q .= ' LEFT JOIN `#__virtuemart_categories` as c ON c.`virtuemart_category_id` = pc.`virtuemart_category_id`'; } $q .= ' WHERE pc.`virtuemart_product_id` = ' . (int)$virtuemart_product_id; if ($front) { $q .= ' AND `published`=1 ORDER BY `c`.`ordering` ASC'; } //$q .= ' ORDER BY `pc`.`ordering` DESC '; $this->_db->setQuery ($q); $categories = $this->_db->loadResultArray (); } return $categories; } /** * Load the product shoppergroups * * @author Kohl Patrick,Max Milbers, Cleanshooter * @return array list of updateProductShoppergroupsTable that can view the product */ private function getProductShoppergroups ($virtuemart_product_id = 0) { $shoppergroups = array(); if ($virtuemart_product_id > 0) { $q = 'SELECT `virtuemart_shoppergroup_id` FROM `#__virtuemart_product_shoppergroups` WHERE `virtuemart_product_id` = "' . (int)$virtuemart_product_id . '"'; $this->_db->setQuery ($q); $shoppergroups = $this->_db->loadResultArray (); } return $shoppergroups; } /** * Get the products in a given category * * @author RolandD * @access public * @param int $virtuemart_category_id the category ID where to get the products for * @return array containing product objects */ public function getProductsInCategory ($categoryId) { $ids = $this->sortSearchListQuery (TRUE, $categoryId); $this->products = $this->getProducts ($ids); return $this->products; } /** * Loads different kind of product lists. * you can load them with calculation or only published onces, very intersting is the loading of groups * valid values are latest, topten, featured, recent. * * The function checks itself by the config if the user is allowed to see the price or published products * * @author Max Milbers */ public function getProductListing ($group = FALSE, $nbrReturnProducts = FALSE, $withCalc = TRUE, $onlyPublished = TRUE, $single = FALSE, $filterCategory = TRUE, $category_id = 0) { $app = JFactory::getApplication (); if ($app->isSite ()) { $front = TRUE; if (!class_exists ('Permissions')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); } if (!Permissions::getInstance ()->check ('admin', 'storeadmin')) { $onlyPublished = TRUE; if ($show_prices = VmConfig::get ('show_prices', 1) == '0') { $withCalc = FALSE; } } } else { $front = FALSE; } $this->setFilter (); if ($filterCategory === TRUE) { if ($category_id) { $this->virtuemart_category_id = $category_id; } } else { $this->virtuemart_category_id = FALSE; } $ids = $this->sortSearchListQuery ($onlyPublished, $this->virtuemart_category_id, $group, $nbrReturnProducts); //quickndirty hack for the BE list, we can do that, because in vm2.1 this is anyway fixed correctly $this->listing = TRUE; $products = $this->getProducts ($ids, $front, $withCalc, $onlyPublished, $single); $this->listing = FALSE; return $products; } /** * overriden getFilter to persist filters * * @author OSP */ public function setFilter () { $app = JFactory::getApplication (); if (!$app->isSite ()) { //persisted filter only in admin $view = JRequest::getWord ('view'); $mainframe = JFactory::getApplication (); $this->virtuemart_category_id = $mainframe->getUserStateFromRequest ('com_virtuemart.' . $view . '.filter.virtuemart_category_id', 'virtuemart_category_id', 0, 'int'); $this->setState ('virtuemart_category_id', $this->virtuemart_category_id); $this->virtuemart_manufacturer_id = $mainframe->getUserStateFromRequest ('com_virtuemart.' . $view . '.filter.virtuemart_manufacturer_id', 'virtuemart_manufacturer_id', 0, 'int'); $this->setState ('virtuemart_manufacturer_id', $this->virtuemart_manufacturer_id); } else { $this->virtuemart_category_id = JRequest::getInt ('virtuemart_category_id', FALSE); } } /** * Returns products for given array of ids * * @author Max Milbers * @param int $productIds * @param boolean $front * @param boolean $withCalc * @param boolean $onlyPublished */ public function getProducts ($productIds, $front = TRUE, $withCalc = TRUE, $onlyPublished = TRUE, $single = FALSE) { if (empty($productIds)) { return array(); } $usermodel = VmModel::getModel ('user'); $currentVMuser = $usermodel->getCurrentUser (); if(!is_array($currentVMuser->shopper_groups)){ $virtuemart_shoppergroup_ids = (array)$currentVMuser->shopper_groups; } else { $virtuemart_shoppergroup_ids = $currentVMuser->shopper_groups; } $maxNumber = VmConfig::get ('absMaxProducts', 700); $products = array(); $i = 0; if ($single) { foreach ($productIds as $id) { if ($product = $this->getProductSingle ((int)$id, $front,1,TRUE,$virtuemart_shoppergroup_ids)) { $products[] = $product; $i++; } if ($i > $maxNumber) { vmdebug ('Better not to display more than ' . $maxNumber . ' products'); return $products; } } } else { foreach ($productIds as $id) { if ($product = $this->getProduct ((int)$id, $front, $withCalc, $onlyPublished, 1, TRUE, $virtuemart_shoppergroup_ids)) { $products[] = $product; $i++; } if ($i > $maxNumber) { vmdebug ('Better not to display more than ' . $maxNumber . ' products'); return $products; } } } return $products; } /** * This function retrieves the "neighbor" products of a product specified by $virtuemart_product_id * Neighbors are the previous and next product in the current list * * @author Max Milbers * @param object $product The product to find the neighours of * @return array */ public function getNeighborProducts ($product, $onlyPublished = TRUE, $max = 1) { $db = JFactory::getDBO (); $neighbors = array('previous' => '', 'next' => ''); $oldDir = $this->filter_order_Dir; $this->_onlyQuery = true; if($this->filter_order_Dir=='ASC'){ $direction = 'DESC'; $op = '<='; } else { $direction = 'ASC'; $op = '>='; } $this->filter_order_Dir = $direction; //We try the method to get exact the next product, the other method would be to get the list of the browse view again and do a match //with the product id and giving back the neighbours $queryArray = $this->sortSearchListQuery($onlyPublished,(int)$product->virtuemart_category_id,false,1); if(isset($queryArray[1])){ $pos= strpos($queryArray[3],'ORDER BY'); $sp = array(); if($pos){ $orderByName = trim(substr ($queryArray[3],($pos+8)) ); $orderByName = str_replace('`','',$orderByName); if(strpos($orderByName,'.')){ $sp = explode('.',$orderByName); $orderByName = $sp[1]; } } $q = 'SELECT p.`virtuemart_product_id`, l.`product_name`, `pc`.ordering FROM `#__virtuemart_products` as p'; $joinT = ''; if(is_array($queryArray[1])){ $joinT = implode('',$queryArray[1]); } $q .= $joinT . ' WHERE (' . implode (' AND ', $queryArray[2]) . ') AND l.`virtuemart_product_id`!="'.$product->virtuemart_product_id.'" '; if(isset($product->$orderByName)){ $orderByValue = $product->$orderByName; if(isset($sp[0])){ $orderByName = '`'.$sp[0].'`.'.$orderByName; } } else { $orderByName = 'product_name'; $orderByValue = $product->product_name; } foreach ($neighbors as &$neighbor) { $qm = ' AND '.$orderByName.' '.$op.' "'.$orderByValue.'" ORDER BY '.$orderByName.' '.$direction.' LIMIT 1'; $db->setQuery ($q.$qm); //vmdebug('getNeighborProducts ',$q.$qm); if ($result = $db->loadAssocList ()) { $neighbor = $result; } if($this->filter_order_Dir=='ASC'){ $direction = 'DESC'; $op = '<='; } else { $direction = 'ASC'; $op = '>='; } } } $this->filter_order_Dir = $oldDir; $this->_onlyQuery = false; return $neighbors; } /* reorder product in one category * TODO this not work perfect ! (Note by Patrick Kohl) */ function saveorder ($cid = array(), $order, $filter = NULL) { JRequest::checkToken () or jexit ('Invalid Token'); $virtuemart_category_id = JRequest::getInt ('virtuemart_category_id', 0); $q = 'SELECT `id`,`ordering` FROM `#__virtuemart_product_categories` WHERE virtuemart_category_id=' . (int)$virtuemart_category_id . ' ORDER BY `ordering` ASC'; $this->_db->setQuery ($q); $pkey_orders = $this->_db->loadObjectList (); $tableOrdering = array(); foreach ($pkey_orders as $orderTmp) { $tableOrdering[$orderTmp->id] = $orderTmp->ordering; } // set and save new ordering foreach ($order as $key => $ord) { $tableOrdering[$key] = $ord; } asort ($tableOrdering); $i = 1; $ordered = 0; foreach ($tableOrdering as $key => $ord) { // if ($order != $i) { $this->_db->setQuery ('UPDATE `#__virtuemart_product_categories` SET `ordering` = ' . $i . ' WHERE `id` = ' . (int)$key . ' '); if (!$this->_db->query ()) { vmError ($this->_db->getErrorMsg ()); return FALSE; } $ordered++; // } $i++; } if ($ordered) { $msg = JText::sprintf ('COM_VIRTUEMART_ITEMS_MOVED', $ordered); } else { $msg = JText::_ ('COM_VIRTUEMART_ITEMS_NOT_MOVED'); } JFactory::getApplication ()->redirect ('index.php?option=com_virtuemart&view=product&virtuemart_category_id=' . $virtuemart_category_id, $msg); } /** * Moves the order of a record * * @param integer The increment to reorder by */ function move ($direction, $filter = NULL) { JRequest::checkToken () or jexit ('Invalid Token'); // Check for request forgeries $table = $this->getTable ('product_categories'); $table->move ($direction); JFactory::getApplication ()->redirect ('index.php?option=com_virtuemart&view=product&virtuemart_category_id=' . JRequest::getInt ('virtuemart_category_id', 0)); } /** * Store a product * * @author Max Milbers * @param $product given as reference * @param bool $isChild Means not that the product is child or not. It means if the product should be threated as child * @return bool */ public function store (&$product, $isChild = FALSE) { JRequest::checkToken () or jexit ('Invalid Token'); if ($product) { $data = (array)$product; } if (!class_exists ('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); $perm = Permissions::getInstance(); $superVendor = $perm->isSuperVendor(); if(empty($superVendor)){ vmError('You are not a vendor or administrator, storing of product cancelled'); return FALSE; } if (isset($data['intnotes'])) { $data['intnotes'] = trim ($data['intnotes']); } // Setup some place holders $product_data = $this->getTable ('products'); if(!empty($data['virtuemart_product_id'])){ $product_data -> load($data['virtuemart_product_id']); } //Set the decimals like product packaging //$decimals = array('product_length','product_width','product_height','product_weight','product_packaging'); foreach($this->decimals as $decimal){ if (array_key_exists ($decimal, $data)) { if(!empty($data[$decimal])){ $data[$decimal] = str_replace(',','.',$data[$decimal]); } else { $data[$decimal] = null; $product_data->$decimal = null; //vmdebug('Store product, set $decimal '.$decimal.' = null'); } } } //with the true, we do preloading and preserve so old values note by Max Milbers // $product_data->bindChecknStore ($data, $isChild); //We prevent with this line, that someone is storing a product as its own parent if(!empty($product_data->product_parent_id) and $product_data->product_parent_id == $data['virtuemart_product_id']){ $product_data->product_parent_id = 0; } $stored = $product_data->bindChecknStore ($data, false); $errors = $product_data->getErrors (); if(!$stored or count($errors)>0){ foreach ($errors as $error) { vmError ('Product store '.$error); } if(!$stored){ vmError('You are not an administrator or the correct vendor, storing of product cancelled'); } return FALSE; } $this->_id = $data['virtuemart_product_id'] = (int)$product_data->virtuemart_product_id; if (empty($this->_id)) { vmError('Product not stored, no id'); return FALSE; } //We may need to change this, the reason it is not in the other list of commands for parents if (!$isChild) { if (!empty($data['save_customfields'])) { if (!class_exists ('VirtueMartModelCustomfields')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'customfields.php'); } VirtueMartModelCustomfields::storeProductCustomfields ('product', $data, $product_data->virtuemart_product_id); } } // Get old IDS $old_price_ids = $this->loadProductPrices($this->_id,0,0,false); //vmdebug('$old_price_ids ',$old_price_ids); if (isset($data['mprices']['product_price']) and count($data['mprices']['product_price']) > 0){ foreach($data['mprices']['product_price'] as $k => $product_price){ $pricesToStore = array(); $pricesToStore['virtuemart_product_id'] = $this->_id; $pricesToStore['virtuemart_product_price_id'] = (int)$data['mprices']['virtuemart_product_price_id'][$k]; if (!$isChild){ //$pricesToStore['basePrice'] = $data['mprices']['basePrice'][$k]; $pricesToStore['product_override_price'] = $data['mprices']['product_override_price'][$k]; $pricesToStore['override'] = (int)$data['mprices']['override'][$k]; $pricesToStore['virtuemart_shoppergroup_id'] = (int)$data['mprices']['virtuemart_shoppergroup_id'][$k]; $pricesToStore['product_tax_id'] = (int)$data['mprices']['product_tax_id'][$k]; $pricesToStore['product_discount_id'] = (int)$data['mprices']['product_discount_id'][$k]; $pricesToStore['product_currency'] = (int)$data['mprices']['product_currency'][$k]; $pricesToStore['product_price_publish_up'] = $data['mprices']['product_price_publish_up'][$k]; $pricesToStore['product_price_publish_down'] = $data['mprices']['product_price_publish_down'][$k]; $pricesToStore['price_quantity_start'] = (int)$data['mprices']['price_quantity_start'][$k]; $pricesToStore['price_quantity_end'] = (int)$data['mprices']['price_quantity_end'][$k]; } if (!$isChild and isset($data['mprices']['use_desired_price'][$k]) and $data['mprices']['use_desired_price'][$k] == "1") { if (!class_exists ('calculationHelper')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php'); } $calculator = calculationHelper::getInstance (); $pricesToStore['salesPrice'] = $data['mprices']['salesPrice'][$k]; $pricesToStore['product_price'] = $data['mprices']['product_price'][$k] = $calculator->calculateCostprice ($this->_id, $pricesToStore); unset($data['mprices']['use_desired_price'][$k]); } else { if(isset($data['mprices']['product_price'][$k]) ){ $pricesToStore['product_price'] = $data['mprices']['product_price'][$k]; } } if ($isChild) $childPrices = $this->loadProductPrices($this->_id,0,0,false); if ((isset($pricesToStore['product_price']) and $pricesToStore['product_price']!='') || (isset($childPrices) and count($childPrices)>1)) { if ($isChild) { //$childPrices = $this->loadProductPrices($pricesToStore['virtuemart_product_price_id'],0,0,false); if(is_array($old_price_ids) and count($old_price_ids)>1){ //We do not touch multiple child prices. Because in the parent list, we see no price, the gui is //missing to reflect the information properly. $pricesToStore = false; $old_price_ids = array(); } else { unset($data['mprices']['product_override_price'][$k]); unset($pricesToStore['product_override_price']); unset($data['mprices']['override'][$k]); unset($pricesToStore['override']); } } //$data['mprices'][$k] = $data['virtuemart_product_id']; if($pricesToStore){ $toUnset = array(); foreach($old_price_ids as $key => $oldprice){ if(array_search($pricesToStore['virtuemart_product_price_id'], $oldprice )){ $pricesToStore = array_merge($oldprice,$pricesToStore); $toUnset[] = $key; } } $this->updateXrefAndChildTables ($pricesToStore, 'product_prices',$isChild); foreach($toUnset as $key){ unset( $old_price_ids[ $key ] ); } } } } } if ( count($old_price_ids) ) { $oldPriceIdsSql = array(); foreach($old_price_ids as $oldPride){ $oldPriceIdsSql[] = $oldPride['virtuemart_product_price_id']; } // delete old unused Prices $this->_db->setQuery( 'DELETE FROM `#__virtuemart_product_prices` WHERE `virtuemart_product_price_id` in ("'.implode('","', $oldPriceIdsSql ).'") '); $this->_db->query(); $err = $this->_db->getErrorMsg(); if(!empty($err)){ vmWarn('In store prodcut, deleting old price error',$err); } } if (!empty($data['childs'])) { foreach ($data['childs'] as $productId => $child) { $child['product_parent_id'] = $data['virtuemart_product_id']; $child['virtuemart_product_id'] = $productId; $this->store ($child, TRUE); } } if (!$isChild) { $data = $this->updateXrefAndChildTables ($data, 'product_shoppergroups'); $data = $this->updateXrefAndChildTables ($data, 'product_manufacturers'); if (!empty($data['categories']) && count ($data['categories']) > 0) { $data['virtuemart_category_id'] = $data['categories']; } else { $data['virtuemart_category_id'] = array(); } $data = $this->updateXrefAndChildTables ($data, 'product_categories'); // Update waiting list //TODO what is this doing? if (!empty($data['notify_users'])) { if ($data['product_in_stock'] > 0 && $data['notify_users'] == '1') { $waitinglist = VmModel::getModel ('Waitinglist'); $waitinglist->notifyList ($data['virtuemart_product_id']); } } // Process the images $mediaModel = VmModel::getModel ('Media'); $mediaModel->storeMedia ($data, 'product'); $errors = $mediaModel->getErrors (); foreach ($errors as $error) { vmError ($error); } } return $product_data->virtuemart_product_id; } public function updateXrefAndChildTables ($data, $tableName, $preload = FALSE) { JRequest::checkToken () or jexit ('Invalid Token'); //First we load the xref table, to get the old data $product_table_Parent = $this->getTable ($tableName); //We must go that way, because the load function of the vmtablexarry // is working different. if($preload){ //$product_table_Parent->setOrderable('ordering',false); $orderingA = $product_table_Parent->load($data['virtuemart_product_id']); } $product_table_Parent->bindChecknStore ($data); $errors = $product_table_Parent->getErrors (); foreach ($errors as $error) { vmError ($error); } return $data; } /** * This function creates a child for a given product id * * @author Max Milbers * @author Patrick Kohl * @param int id of parent id */ public function createChild ($id) { // created_on , modified_on $db = JFactory::getDBO (); $vendorId = 1; $childs = count ($this->getProductChildIds ($id)); $db->setQuery ('SELECT `product_name`,`slug` FROM `#__virtuemart_products` JOIN `#__virtuemart_products_' . VMLANG . '` as l using (`virtuemart_product_id`) WHERE `virtuemart_product_id`=' . (int)$id); $parent = $db->loadObject (); $prodTable = $this->getTable ('products'); //$newslug = $parent->slug . $id . rand (1, 9); $newslug = $prodTable->checkCreateUnique('products_' . VmConfig::$vmlang,$parent->slug); $data = array('product_name' => $parent->product_name, 'slug' => $newslug, 'virtuemart_vendor_id' => (int)$vendorId, 'product_parent_id' => (int)$id); $prodTable->bindChecknStore ($data); $langs = (array)VmConfig::get ('active_languages'); if (count ($langs) > 1) { foreach ($langs as $lang) { $lang = str_replace ('-', '_', strtolower ($lang)); $db->setQuery ('SELECT `product_name` FROM `#__virtuemart_products_' . $lang . '` WHERE `virtuemart_product_id` = "' . $prodTable->virtuemart_product_id . '" '); $res = $db->loadResult (); if (!$res) { $db->setQuery ('INSERT INTO `#__virtuemart_products_' . $lang . '` (`virtuemart_product_id`,`slug`) VALUES ("' . $prodTable->virtuemart_product_id . '","' . $newslug . '");'); $db->query (); $err = $db->getErrorMsg (); if (!empty($err)) { vmError ('Database error: createChild ' . $err); } } } } return $data['virtuemart_product_id']; } /** * Creates a clone of a given product id * * @author Max Milbers * @param int $virtuemart_product_id */ public function createClone ($id) { // if (is_array($cids)) $cids = array($cids); $product = $this->getProduct ($id, FALSE, FALSE, FALSE); $product->field = $this->productCustomsfieldsClone ($id); // vmdebug('$product->field',$product->field); $product->virtuemart_product_id = $product->virtuemart_product_price_id = 0; $product->mprices = $this->productPricesClone ($id); //Lets check if the user is admin or the mainvendor if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); $admin = Permissions::getInstance()->check('admin'); if($admin){ $product->created_on = "0000-00-00 00:00:00"; $product->created_by = 0; } $product->slug = $product->slug . '-' . $id; $product->save_customfields = 1; JPluginHelper::importPlugin ('vmcustom'); $dispatcher = JDispatcher::getInstance (); $result=$dispatcher->trigger ('plgVmCloneProduct', array(&$product)); $this->store ($product); return $this->_id; } private function productPricesClone ($virtuemart_product_id) { $this->_db = JFactory::getDBO (); $q = "SELECT * FROM `#__virtuemart_product_prices`"; $q .= " WHERE `virtuemart_product_id` = " . $virtuemart_product_id; $this->_db->setQuery ($q); $prices = $this->_db->loadAssocList (); if ($prices) { foreach ($prices as $k => &$price) { unset($price['virtuemart_product_id'], $price['virtuemart_product_price_id']); if(empty($mprices[$k])) $mprices[$k] = array(); foreach ($price as $i => $value) { if(empty($mprices[$i])) $mprices[$i] = array(); $mprices[$i][$k] = $value; } } return $mprices; } else { return NULL; } } /* look if whe have a product type */ private function productCustomsfieldsClone ($virtuemart_product_id) { $this->_db = JFactory::getDBO (); $q = "SELECT * FROM `#__virtuemart_product_customfields`"; $q .= " WHERE `virtuemart_product_id` = " . $virtuemart_product_id; $this->_db->setQuery ($q); $customfields = $this->_db->loadAssocList (); if ($customfields) { foreach ($customfields as &$customfield) { unset($customfield['virtuemart_product_id'], $customfield['virtuemart_customfield_id']); } return $customfields; } else { return NULL; } } /** * removes a product and related table entries * * @author Max Milberes */ public function remove ($ids) { $table = $this->getTable ($this->_maintablename); $cats = $this->getTable ('product_categories'); $customfields = $this->getTable ('product_customfields'); $manufacturers = $this->getTable ('product_manufacturers'); $medias = $this->getTable ('product_medias'); $prices = $this->getTable ('product_prices'); $shop = $this->getTable ('product_shoppergroups'); $rating = $this->getTable ('ratings'); $review = $this->getTable ('rating_reviews'); $votes = $this->getTable ('rating_votes'); $ok = TRUE; foreach ($ids as $id) { $childIds = $this->getProductChildIds ($id); if (!empty($childIds)) { vmError (JText::_ ('COM_VIRTUEMART_PRODUCT_CANT_DELETE_CHILD')); $ok = FALSE; continue; } if (!$table->delete ($id)) { vmError ('Product delete ' . $table->getError ()); $ok = FALSE; } if (!$cats->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete categories ' . $cats->getError ()); $ok = FALSE; } if (!$customfields->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete customs ' . $customfields->getError ()); $ok = FALSE; } $db = JFactory::getDbo(); $q = 'SELECT `virtuemart_customfield_id` FROM `#__virtuemart_product_customfields` as pc '; $q .= 'LEFT JOIN `#__virtuemart_customs`as c using (`virtuemart_custom_id`) WHERE pc.`custom_value` = "' . $id . '" AND `field_type`= "R"'; $db->setQuery($q); $list = $db->loadResultArray(); if ($list) { $listInString = implode(',',$list); //Delete media xref $query = 'DELETE FROM `#__virtuemart_product_customfields` WHERE `virtuemart_customfield_id` IN ('. $listInString .') '; $this->_db->setQuery($query); if(!$this->_db->query()){ vmError( $this->_db->getErrorMsg() ); } } if (!$manufacturers->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete manufacturer ' . $manufacturers->getError ()); $ok = FALSE; } if (!$medias->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete medias ' . $medias->getError ()); $ok = FALSE; } if (!$prices->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete prices ' . $prices->getError ()); $ok = FALSE; } if (!$shop->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete shoppergroups ' . $shop->getError ()); $ok = FALSE; } if (!$rating->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete rating ' . $rating->getError ()); $ok = FALSE; } if (!$review->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete reviews ' . $review->getError ()); $ok = FALSE; } if (!$votes->delete ($id, 'virtuemart_product_id')) { vmError ('Product delete votes ' . $votes->getError ()); $ok = FALSE; } // delete plugin on product delete // $ok must be set to false if an error occurs JPluginHelper::importPlugin ('vmcustom'); $dispatcher = JDispatcher::getInstance (); $dispatcher->trigger ('plgVmOnDeleteProduct', array($id, &$ok)); } return $ok; } /** * Gets the price for a variant * * @author Max Milbers */ public function getPrice ($product, $customVariant, $quantity) { $this->_db = JFactory::getDBO (); // vmdebug('strange',$product); if (!is_object ($product)) { // vmError('deprecated use of getPrice'); $product = $this->getProduct ($product, TRUE, FALSE, TRUE,$quantity); // return false; } // Loads the product price details if (!class_exists ('calculationHelper')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php'); } $calculator = calculationHelper::getInstance (); // Calculate the modificator $variantPriceModification = $calculator->calculateModificators ($product, $customVariant); $prices = $calculator->getProductPrices ($product, $variantPriceModification, $quantity); return $prices; } /** * Get the Order By Select List * * notice by Max Milbers html tags should never be in a model. This function should be moved to a helper or simular,... * * @author Kohl Patrick * @access public * @param $fieds from config Back-end * @return $orderByList * Order,order By, manufacturer and category link List to echo Out **/ function getOrderByList ($virtuemart_category_id = FALSE) { $getArray = (JRequest::get ('get')); $link = ''; $fieldLink = ''; // remove setted variable unset ($getArray['globalCurrencyConverter'], $getArray['virtuemart_manufacturer_id'], $getArray['order'], $getArray['orderby']); // foreach ($getArray as $key => $value ) // $fieldLink .= '&'.$key.'='.$value; //vmdebug('getOrderByList',$getArray); foreach ($getArray as $key => $value) { if (is_array ($value)) { foreach ($value as $k => $v) { $fieldLink .= '&' . $key . '[' . $k . ']' . '=' . $v; } } else { if($key=='dir' or $key=='orderby') continue; if(empty($value)) continue; $fieldLink .= '&' . $key . '=' . $value; } } $fieldLink[0] = "?"; $fieldLink = 'index.php' . $fieldLink; $orderDirLink = ''; $orderDirConf = VmConfig::get ('prd_brws_orderby_dir'); $orderDir = JRequest::getWord ('dir', $orderDirConf); if ($orderDir != $orderDirConf ) { $orderDirLink .= '&dir=' . $orderDir; //was '&order=' } $orderbyTxt = ''; $orderby = JRequest::getVar ('orderby', VmConfig::get ('browse_orderby_field')); $orderby = $this->checkFilterOrder ($orderby); $orderbyCfg = VmConfig::get ('browse_orderby_field'); if ($orderby != $orderbyCfg) { $orderbyTxt = '&orderby=' . $orderby; } $manufacturerTxt = ''; $manufacturerLink = ''; if (VmConfig::get ('show_manufacturers')) { // manufacturer link list $virtuemart_manufacturer_id = JRequest::getInt ('virtuemart_manufacturer_id', ''); if ($virtuemart_manufacturer_id != '') { $manufacturerTxt = '&virtuemart_manufacturer_id=' . $virtuemart_manufacturer_id; } // if ($mf_virtuemart_product_ids) { $query = 'SELECT DISTINCT l.`mf_name`,l.`virtuemart_manufacturer_id` FROM `#__virtuemart_manufacturers_' . VMLANG . '` as l'; $query .= ' JOIN `#__virtuemart_product_manufacturers` AS pm using (`virtuemart_manufacturer_id`)'; $query .= ' LEFT JOIN `#__virtuemart_products` as p ON p.`virtuemart_product_id` = pm.`virtuemart_product_id` '; $query .= ' LEFT JOIN `#__virtuemart_product_categories` as c ON c.`virtuemart_product_id` = pm.`virtuemart_product_id` '; $query .= ' WHERE p.`published` =1'; if ($virtuemart_category_id) { $query .= ' AND c.`virtuemart_category_id` =' . (int)$virtuemart_category_id; } $query .= ' ORDER BY l.`mf_name`'; $this->_db->setQuery ($query); $manufacturers = $this->_db->loadObjectList (); // vmdebug('my manufacturers',$this->_db->getQuery()); $manufacturerLink = ''; if (count ($manufacturers) > 0) { $manufacturerLink = '
'; if ($virtuemart_manufacturer_id > 0) { $manufacturerLink .= ''; } if (count ($manufacturers) > 1) { foreach ($manufacturers as $mf) { $link = JRoute::_ ($fieldLink . '&virtuemart_manufacturer_id=' . $mf->virtuemart_manufacturer_id . $orderbyTxt . $orderDirLink,FALSE); if ($mf->virtuemart_manufacturer_id != $virtuemart_manufacturer_id) { $manufacturerLink .= ''; } else { $currentManufacturerLink = '
' . JText::_ ('COM_VIRTUEMART_PRODUCT_DETAILS_MANUFACTURER_LBL') . '
' . $mf->mf_name . '
'; } } } elseif ($virtuemart_manufacturer_id > 0) { $currentManufacturerLink = '
' . JText::_ ('COM_VIRTUEMART_PRODUCT_DETAILS_MANUFACTURER_LBL') . '
' . $manufacturers[0]->mf_name . '
'; } else { $currentManufacturerLink = '
' . JText::_ ('COM_VIRTUEMART_PRODUCT_DETAILS_MANUFACTURER_LBL') . '
' . $manufacturers[0]->mf_name . '
'; } $manufacturerLink .= '
'; } // } } /* order by link list*/ $orderByLink = ''; $fields = VmConfig::get ('browse_orderby_fields'); if (count ($fields) > 1) { $orderByLink = '
'; foreach ($fields as $field) { if ($field != $orderby) { $dotps = strrpos ($field, '.'); if ($dotps !== FALSE) { $prefix = substr ($field, 0, $dotps + 1); $fieldWithoutPrefix = substr ($field, $dotps + 1); // vmdebug('Found dot '.$dotps.' $prefix '.$prefix.' $fieldWithoutPrefix '.$fieldWithoutPrefix); } else { $prefix = ''; $fieldWithoutPrefix = $field; } $text = JText::_ ('COM_VIRTUEMART_' . strtoupper ($fieldWithoutPrefix)); $field = explode('.',$field); if(isset($field[1])){ $field = $field[1]; } else { $field = $field[0]; } $link = JRoute::_ ($fieldLink . $manufacturerTxt . '&orderby=' . $field,FALSE); $orderByLink .= ''; } } $orderByLink .= '
'; } if($orderDir == 'ASC'){ $orderDir = 'DESC'; } else { $orderDir = 'ASC'; } if ($orderDir != $orderDirConf ) { $orderDirLink = '&dir=' . $orderDir; //was '&order=' } else { $orderDirLink = ''; } //$orderDirTxt = JText::_ ('COM_VIRTUEMART_SEARCH_ORDER_'.$orderDir); $orderDirTxt = JText::_ ('COM_VIRTUEMART_'.$orderDir); $link = JRoute::_ ($fieldLink . $orderbyTxt . $orderDirLink . $manufacturerTxt,FALSE); // full string list if ($orderby == '') { $orderby = $orderbyCfg; } $orderby = strtoupper ($orderby); $dotps = strrpos ($orderby, '.'); if ($dotps !== FALSE) { $prefix = substr ($orderby, 0, $dotps + 1); $orderby = substr ($orderby, $dotps + 1); // vmdebug('Found dot '.$dotps.' $prefix '.$prefix.' $fieldWithoutPrefix '.$fieldWithoutPrefix); } else { $prefix = ''; // $orderby = $orderby; } $orderByList = '
' . JText::_ ('COM_VIRTUEMART_ORDERBY') . '
'; $orderByList .= $orderByLink . '
'; $manuList = ''; if (VmConfig::get ('show_manufacturers')) { if (empty ($currentManufacturerLink)) { $currentManufacturerLink = '
' . JText::_ ('COM_VIRTUEMART_PRODUCT_DETAILS_MANUFACTURER_LBL') . '
' . JText::_ ('COM_VIRTUEMART_SEARCH_SELECT_MANUFACTURER') . '
'; } $manuList = '
' . $currentManufacturerLink; $manuList .= $manufacturerLink . '
'; } return array('orderby'=> $orderByList, 'manufacturer'=> $manuList); } // ************************************************** //Stocks // /** * Get the stock level for a given product * * @author RolandD * @access public * @param object $product the product to get stocklevel for * @return array containing product objects */ public function getStockIndicator ($product) { $this->_db = JFactory::getDBO (); /* Assign class to indicator */ $stock_level = $product->product_in_stock - $product->product_ordered; $reorder_level = $product->low_stock_notification; $level = 'normalstock'; $stock_tip = JText::_ ('COM_VIRTUEMART_STOCK_LEVEL_DISPLAY_NORMAL_TIP'); if ($stock_level <= $reorder_level) { $level = 'lowstock'; $stock_tip = JText::_ ('COM_VIRTUEMART_STOCK_LEVEL_DISPLAY_LOW_TIP'); } if ($stock_level <= 0) { $level = 'nostock'; $stock_tip = JText::_ ('COM_VIRTUEMART_STOCK_LEVEL_DISPLAY_OUT_TIP'); } $stock = new Stdclass(); $stock->stock_tip = $stock_tip; $stock->stock_level = $level; return $stock; } public function updateStockInDB ($product, $amount, $signInStock, $signOrderedStock) { // vmdebug( 'stockupdate in DB', $product->virtuemart_product_id,$amount, $signInStock, $signOrderedStock ); $validFields = array('=', '+', '-'); if (!in_array ($signInStock, $validFields)) { return FALSE; } if (!in_array ($signOrderedStock, $validFields)) { return FALSE; } //sanitize fields $id = (int)$product->virtuemart_product_id; $amount = (float)$amount; $update = array(); if ($signInStock != '=' or $signOrderedStock != '=') { if ($signInStock != '=') { $update[] = '`product_in_stock` = `product_in_stock` ' . $signInStock . $amount; if (strpos ($signInStock, '+') !== FALSE) { $signInStock = '-'; } else { $signInStock = '+'; } $update[] = '`product_sales` = `product_sales` ' . $signInStock . $amount; } if ($signOrderedStock != '=') { $update[] = '`product_ordered` = `product_ordered` ' . $signOrderedStock . $amount; } $q = 'UPDATE `#__virtuemart_products` SET ' . implode (", ", $update) . ' WHERE `virtuemart_product_id` = ' . $id; $this->_db->setQuery ($q); $this->_db->query (); //The low on stock notification comes now, when the people ordered. //You need to know that the stock is going low before you actually sent the wares, because then you ususally know it already yoursefl //note by Max Milbers if ($signInStock == '+') { $this->_db->setQuery ('SELECT (IFNULL(`product_in_stock`,"0")+IFNULL(`product_ordered`,"0")) < IFNULL(`low_stock_notification`,"0") ' . 'FROM `#__virtuemart_products` ' . 'WHERE `virtuemart_product_id` = ' . $id ); if ($this->_db->loadResult () == 1) { $this->lowStockWarningEmail( $id) ; } } } } function lowStockWarningEmail($virtuemart_product_id) { if(VmConfig::get('lstockmail',TRUE)){ if (!class_exists ('shopFunctionsF')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'shopfunctionsf.php'); } /* Load the product details */ $q = "SELECT l.product_name,product_in_stock FROM `#__virtuemart_products_" . VMLANG . "` l JOIN `#__virtuemart_products` p ON p.virtuemart_product_id=l.virtuemart_product_id WHERE p.virtuemart_product_id = " . $virtuemart_product_id; $this->_db->setQuery ($q); $vars = $this->_db->loadAssoc (); $url = JURI::root () . 'index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=' . $virtuemart_product_id; $link = ''. $vars['product_name'].''; $vars['subject'] = JText::sprintf('COM_VIRTUEMART_PRODUCT_LOW_STOCK_EMAIL_SUBJECT',$vars['product_name']); $vars['mailbody'] =JText::sprintf('COM_VIRTUEMART_PRODUCT_LOW_STOCK_EMAIL_BODY',$link, $vars['product_in_stock']); $virtuemart_vendor_id = 1; $vendorModel = VmModel::getModel ('vendor'); $vendor = $vendorModel->getVendor ($virtuemart_vendor_id); $vendorModel->addImages ($vendor); $vars['vendor'] = $vendor; $vars['vendorAddress']= shopFunctions::renderVendorAddress($virtuemart_vendor_id); $vars['vendorEmail'] = $vendorModel->getVendorEmail ($virtuemart_vendor_id); $vars['user'] = $vendor->vendor_store_name ; shopFunctionsF::renderMail ('productdetails', $vars['vendorEmail'], $vars, 'productdetails', TRUE) ; return TRUE; } else { return FALSE; } } public function getUncategorizedChildren ($withParent) { if (empty($this->_uncategorizedChildren[$this->_id])) { //Todo add check for shoppergroup depended product display $q = 'SELECT * FROM `#__virtuemart_products` as p LEFT JOIN `#__virtuemart_products_' . VMLANG . '` as pl USING (`virtuemart_product_id`) LEFT JOIN `#__virtuemart_product_categories` as pc USING (`virtuemart_product_id`) '; // $q .= ' WHERE (`product_parent_id` = "'.$this->_id.'" AND (pc.`virtuemart_category_id`) IS NULL ) OR (`virtuemart_product_id` = "'.$this->_id.'" ) '; if ($withParent) { $q .= ' WHERE (`product_parent_id` = "' . $this->_id . '" OR `virtuemart_product_id` = "' . $this->_id . '") '; } else { $q .= ' WHERE `product_parent_id` = "' . $this->_id . '" '; } $app = JFactory::getApplication (); if ($app->isSite () && !VmConfig::get ('use_as_catalog', 0) && VmConfig::get ('stockhandle', 'none') == 'disableit') { $q .= ' AND p.`product_in_stock`>"0" '; } if ($app->isSite ()) { $q .= ' AND p.`published`="1"'; } $q .= ' GROUP BY `virtuemart_product_id` ORDER BY p.pordering ASC'; $this->_db->setQuery ($q); $this->_uncategorizedChildren[$this->_id] = $this->_db->loadAssocList (); $err = $this->_db->getErrorMsg (); if (!empty($err)) { vmError ('getUncategorizedChildren sql error ' . $err, 'getUncategorizedChildren sql error'); vmdebug ('getUncategorizedChildren ' . $err); return FALSE; } // vmdebug('getUncategorizedChildren '.$this->_db->getQuery(),$this->_uncategorizedChildren); } return $this->_uncategorizedChildren[$this->_id]; } /** * Check if the product has any children * * @author RolandD * @author Max Milbers * @param int $virtuemart_product_id Product ID * @return bool True if there are child products, false if there are no child products */ public function checkChildProducts ($virtuemart_product_id) { $q = 'SELECT IF(COUNT(virtuemart_product_id) > 0, "0", "1") FROM `#__virtuemart_products` WHERE `product_parent_id` = "' . (int)$virtuemart_product_id . '"'; $this->_db->setQuery ($q); return $this->_db->loadResult (); } function getProductChilds ($product_id) { if (empty($product_id)) { return array(); } $db = JFactory::getDBO (); $db->setQuery (' SELECT virtuemart_product_id, product_name FROM `#__virtuemart_products_' . VMLANG . '` JOIN `#__virtuemart_products` as C using (`virtuemart_product_id`) WHERE `product_parent_id` =' . (int)$product_id); return $db->loadObjectList (); } function getProductChildIds ($product_id) { if (empty($product_id)) { return array(); } $db = JFactory::getDBO (); $db->setQuery (' SELECT virtuemart_product_id FROM `#__virtuemart_products` WHERE `product_parent_id` =' . (int)$product_id.' ORDER BY pordering ASC'); return $db->loadResultArray (); } function getProductParent ($product_parent_id) { if (empty($product_parent_id)) { return array(); } $db = JFactory::getDBO (); $db->setQuery (' SELECT * FROM `#__virtuemart_products_' . VMLANG . '` WHERE `virtuemart_product_id` =' . (int)$product_parent_id); return $db->loadObject (); } function sentProductEmailToShoppers () { jimport ('joomla.utilities.arrayhelper'); if (!class_exists ('ShopFunctions')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'shopfunctions.php'); } $product_id = JRequest::getVar ('virtuemart_product_id', ''); vmdebug ('sentProductEmailToShoppers product id', $product_id); $vars = array(); $vars['subject'] = JRequest::getVar ('subject'); $vars['mailbody'] = JRequest::getVar ('mailbody'); $order_states = JRequest::getVar ('statut', array(), '', 'ARRAY'); $productShoppers = $this->getProductShoppersByStatus ($product_id, $order_states); vmdebug ('productShoppers ', $productShoppers); $productModel = VmModel::getModel ('product'); $product = $productModel->getProduct ($product_id); $vendorModel = VmModel::getModel ('vendor'); $vendor = $vendorModel->getVendor ($product->virtuemart_vendor_id); $vendorModel->addImages ($vendor); $vars['vendor'] = $vendor; $vars['vendorEmail'] = $vendorModel->getVendorEmail ($product->virtuemart_vendor_id); $vars['vendorAddress'] = shopFunctions::renderVendorAddress ($product->virtuemart_vendor_id); $orderModel = VmModel::getModel ('orders'); foreach ($productShoppers as $productShopper) { $vars['user'] = $productShopper['name']; if (shopFunctionsF::renderMail ('productdetails', $productShopper['email'], $vars, 'productdetails', TRUE)) { $string = 'COM_VIRTUEMART_MAIL_SEND_SUCCESSFULLY'; } else { $string = 'COM_VIRTUEMART_MAIL_NOT_SEND_SUCCESSFULLY'; } /* Update the order history for each order */ foreach ($productShopper['order_info'] as $order_info) { $orderModel->_updateOrderHist ($order_info['order_id'], $order_info['order_status'], 1, $vars['subject'] . ' ' . $vars['mailbody']); } // todo: when there is an error while sending emails //vmInfo (JText::sprintf ($string, $productShopper['email'])); } } public function getProductShoppersByStatus ($product_id, $states) { if (empty($states)) { return FALSE; } $orderstatusModel = VmModel::getModel ('orderstatus'); $orderStates = $orderstatusModel->getOrderStatusNames (); foreach ($states as &$status) { if (!array_key_exists ($status, $orderStates)) { unset($status); } } if (empty($states)) { return FALSE; } $q = 'SELECT ou.* , oi.product_quantity , o.order_number, o.order_status, oi.`order_status` AS order_item_status , o.virtuemart_order_id FROM `#__virtuemart_order_userinfos` as ou JOIN `#__virtuemart_order_items` AS oi USING (`virtuemart_order_id`) JOIN `#__virtuemart_orders` AS o ON o.`virtuemart_order_id` = oi.`virtuemart_order_id` WHERE ou.`address_type`="BT" AND oi.`virtuemart_product_id`=' . (int)$product_id; if (count ($orderStates) !== count ($states)) { $q .= ' AND oi.`order_status` IN ( "' . implode ('","', $states) . '") '; } $q .= ' ORDER BY ou.`email` ASC'; $this->_db->setQuery ($q); $productShoppers = $this->_db->loadAssocList (); $shoppers = array(); foreach ($productShoppers as $productShopper) { $key = $productShopper['email']; if (!array_key_exists ($key, $shoppers)) { $shoppers[$key]['phone'] = !empty($productShopper['phone_1']) ? $productShopper['phone_1'] : (!empty($productShopper['phone_2']) ? $productShopper['phone_2'] : '-'); $shoppers[$key]['name'] = $productShopper['first_name'] . ' ' . $productShopper['last_name']; $shoppers[$key]['email'] = $productShopper['email']; $shoppers[$key]['mail_to'] = 'mailto:' . $productShopper['email']; $shoppers[$key]['nb_orders'] = 0; } $i = $shoppers[$key]['nb_orders']; $shoppers[$key]['order_info'][$i]['order_number'] = $productShopper['order_number']; $shoppers[$key]['order_info'][$i]['order_id'] = $productShopper['virtuemart_order_id']; $shoppers[$key]['order_info'][$i]['order_status'] = $productShopper['order_status']; $shoppers[$key]['order_info'][$i]['order_item_status_name'] = $orderStates[$productShopper['order_item_status']]['order_status_name']; $shoppers[$key]['order_info'][$i]['quantity'] = $productShopper['product_quantity']; $shoppers[$key]['nb_orders']++; } return $shoppers; } } // No closing tagcurrency.php000066600000010046151372127700007121 0ustar00setMainTable('currencies'); } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * * @author Max Milbers */ function getCurrency($currency_id=0) { if(!empty($currency_id)) $this->setId((int)$currency_id); if (empty($this->_data) ) { $this->_data = $this->getTable('currencies'); $this->_data->load((int)$this->_id); } return $this->_data; } /** * Retireve a list of currencies from the database. * This function is used in the backend for the currency listing, therefore no asking if enabled or not * @author Max Milbers * @return object List of currency objects */ function getCurrenciesList($search,$vendorId=1) { $where = array(); // $this->_query = 'SELECT * FROM `#__virtuemart_currencies` '; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if( !Permissions::getInstance()->check('admin') ){ $where[] = '(`virtuemart_vendor_id` = "'.(int)$vendorId.'" OR `shared`="1")'; } if(empty($search)){ $search = JRequest::getString('search', false); } /* add filters */ if($search){ $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; //$search = $this->_db->Quote($search, false); $where[] = '`currency_name` LIKE '.$search.' OR `currency_code_2` LIKE '.$search.' OR `currency_code_3` LIKE '.$search; } // if (JRequest::getString('search', false)) $where[] = '`currency_name` LIKE "%'.$this->_db->getEscaped(JRequest::getString('search')).'%"'; $whereString=''; if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where) ; // if (count($where) > 0) $this->_query .= ' WHERE '.implode(' AND ', $where) ; // $this->_query .= $this->_getOrdering('currency_name'); // $this->_data = $this->_getList($this->_query, $this->getState('limitstart'), $this->getState('limit')); // $this->_total = $this->_getListCount($this->_query) ; // $object, $select, $joinedTables, $whereString = '', $groupBy = '', $orderBy = '', $filter_order_Dir = '', $nbrReturnProducts = false $this->_data = $this->exeSortSearchListQuery(0,'*',' FROM `#__virtuemart_currencies`',$whereString,'',$this->_getOrdering()); return $this->_data; // return $this->_data; } /** * Retireve a list of currencies from the database. * * This is written to get a list for selecting currencies. Therefore it asks for enabled * @author Max Milbers * @return object List of currency objects */ function getCurrencies($vendorId=1) { $db = JFactory::getDBO(); $q = 'SELECT * FROM `#__virtuemart_currencies` WHERE (`virtuemart_vendor_id` = "'.(int)$vendorId.'" OR `shared`="1") AND published = "1" ORDER BY `#__virtuemart_currencies`.`currency_name`'; $db->setQuery($q); return $db->loadObjectList(); } } // pure php no closing tagupdatesmigration.php000066600000051441151372127700010652 0ustar00 0) { $this->_user = JFactory::getUser($virtuemart_user_id); } else { $this->_user = JFactory::getUser(); } return $this->_user->id; } /** * @author Max Milbers */ function setStoreOwner($userId=-1) { $allowInsert=FALSE; if($userId===-1){ $allowInsert = TRUE; $userId = 0; } if (empty($userId)) { $userId = $this->determineStoreOwner(); vmdebug('setStoreOwner $userId = '.$userId.' by determineStoreOwner'); } $db = JFactory::getDBO(); $db->setQuery('SELECT * FROM `#__virtuemart_vmusers` WHERE `virtuemart_user_id`= "' . $userId . '" '); $oldUserId = $db->loadResult(); if (!empty($oldUserId) and !empty($userId)) { $db->setQuery( 'UPDATE `#__virtuemart_vmusers` SET `virtuemart_vendor_id` = "0", `user_is_vendor` = "0", `perms` = "" WHERE `virtuemart_vendor_id` ="1" '); if ($db->query() == false ) { JError::raiseWarning(1, 'UPDATE __vmusers failed for virtuemart_user_id '.$userId); return false; } $db->setQuery( 'UPDATE `#__virtuemart_vmusers` SET `virtuemart_vendor_id` = "1", `user_is_vendor` = "1", `perms` = "admin" WHERE `virtuemart_user_id` ="'.$userId.'" '); if ($db->query() === false ) { JError::raiseWarning(1, 'UPDATE __vmusers failed for virtuemart_user_id '.$userId); return false; } else { vmInfo('setStoreOwner VmUser updated new main vendor has user id '.$userId); } } else if($allowInsert){ $db->setQuery('INSERT `#__virtuemart_vmusers` (`virtuemart_user_id`, `user_is_vendor`, `virtuemart_vendor_id`, `perms`) VALUES ("' . $userId . '", "1","1","admin")'); if ($db->query() === false ) { JError::raiseWarning(1, 'setStoreOwner was not possible to execute INSERT __vmusers for virtuemart_user_id '.$userId); return false; } else { vmInfo('setStoreOwner VmUser inserted new main vendor has user id '.$userId); } } return $userId; } /** * Syncs user permission * * @param int virtuemart_user_id * @return bool true on success * @author Christopher Roussel */ function setUserToPermissionGroup ($userId=0) { if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); $usersTable = $this->getTable('vmusers'); $usersTable->load((int)$userId); $perm = Permissions::getInstance(); $usersTable->perms = $perm->getPermissions($userId); $result = $usersTable->check(); if ($result) { $result = $usersTable->store(); } if (!$result) { $errors = $usersTable->getErrors(); foreach($errors as $error) { vmError(get_class( $this ).'::setUserToPermissionGroup user '.$error); } return false; } $xrefTable = $this->getTable('vmuser_shoppergroups'); $data = $xrefTable->load((int)$userId); if (empty($data)) { $data = array('virtuemart_user_id'=>$userId, 'virtuemart_shoppergroup_id'=>'0'); if (!$xrefTable->save($data)) { $errors = $xrefTable->getErrors(); foreach($errors as $error){ vmError(get_class( $this ).'::setUserToPermissionGroup xref '.$error); } return false; } } return true; } /** * Installs sample data to the current database. * * @author Max Milbers, RickG * @params $userId User Id to add the userinfo and vendor sample data to */ function installSampleData($userId = null) { if ($userId == null) { $userId = $this->determineStoreOwner(); } $fields['username'] = $this->_user->username; $fields['virtuemart_user_id'] = $userId; $fields['address_type'] = 'BT'; // Don't change this company name; it's used in install_sample_data.sql $fields['company'] = "Sample Company"; $fields['title'] = 'Mr'; $fields['last_name'] = 'John'; $fields['first_name'] = 'Doe'; $fields['middle_name'] = ''; $fields['phone_1'] = '555-555-555'; $fields['address_1'] = 'PO Box 123'; $fields['city'] = 'Seattle'; $fields['zip'] = '98101'; $fields['virtuemart_state_id'] = '48'; $fields['virtuemart_country_id'] = '223'; // $fields['virtuemart_shoppergroup_id'] = ''; //Dont change this, atm everything is mapped to mainvendor with id=1 $fields['user_is_vendor'] = '1'; $fields['virtuemart_vendor_id'] = '1'; $fields['vendor_name'] = 'Sample Company'; $fields['vendor_phone'] = '555-555-1212'; $fields['vendor_store_name'] = "VirtueMart 2 Sample store"; $fields['vendor_store_desc'] = '

We have the best clothing for up-to-date people. Check it out!

We were established in 1869 in a time when getting good clothes was expensive, but the quality was good. Now that only a select few of those authentic clothes survive, we have dedicated this store to bringing the experience alive for collectors and master carrier everywhere.

You can easily find products selecting the category you would like to browse above.

'; $fields['virtuemart_media_id'] = 1; $fields['vendor_currency'] = '47'; $fields['vendor_accepted_currencies'] = '52,26,47,144'; $fields['vendor_terms_of_service'] = '
You have not configured any terms of service yet. Click here to change this text.
'; $fields['vendor_url'] = JURI::root(); $fields['vendor_name'] = 'Sample Company'; $fields['perms']='admin'; $fields['vendor_legal_info']="VAT-ID: XYZ-DEMO
Reg.Nr: DEMONUMBER"; $fields['vendor_letter_css']='.vmdoc-header { }.vmdoc-footer { }'; $fields['vendor_letter_header_html']='

{vm:vendorname}

{vm:vendoraddress}

'; $fields['vendor_letter_header_image']='1'; $fields['vendor_letter_footer_html']='{vm:vendorlegalinfo}
Page {vm:pagenum}/{vm:pagecount}'; if(!class_exists('VirtueMartModelUser')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'user.php'); $usermodel = VmModel::getModel('user'); $usermodel->setId($userId); //Save the VM user stuff if(!$usermodel->store($fields)){ vmError(JText::_('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USER_DATA') ); JError::raiseWarning('', JText::_('COM_VIRTUEMART_RAISEWARNING_NOT_ABLE_TO_SAVE_USER_DATA')); } // $params = JComponentHelper::getParams('com_languages'); // $lang = $params->get('site', 'en-GB');//use default joomla // $this->installSampleSQL($lang); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'install_sample_data.sql'; if(!defined('VMLANG')){ $params = JComponentHelper::getParams('com_languages'); $lang = $params->get('site', 'en-GB');//use default joomla $lang = strtolower(strtr($lang,'-','_')); } else { $lang = VMLANG; } if(!$this->execSQLFile($filename)){ vmError(JText::_('Problems execution of SQL File '.$filename)); } else { //update jplugin_id from shipment and payment $db = JFactory::getDBO(); $q = 'SELECT `extension_id` FROM #__extensions WHERE element = "weight_countries" AND folder = "vmshipment"'; $db->setQuery($q); $shipment_plg_id = $db->loadResult(); if(!empty($shipment_plg_id)){ $q = 'INSERT INTO `#__virtuemart_shipmentmethods` (`virtuemart_shipmentmethod_id`, `virtuemart_vendor_id`, `shipment_jplugin_id`, `shipment_element`, `shipment_params`, `ordering`, `shared`, `published`, `created_on`, `created_by`, `modified_on`, `modified_by`, `locked_on`, `locked_by`) VALUES (1, 1, '.$shipment_plg_id.', "weight_countries", \'shipment_logos=""|countries=""|zip_start=""|zip_stop=""|weight_start=""|weight_stop=""|weight_unit="KG"|nbproducts_start=0|nbproducts_stop=0|orderamount_start=""|orderamount_stop=""|cost="0"|package_fee="2.49"|tax_id="0"|free_shipment="500"|\', 0, 0, 1, "0000-00-00 00:00:00", 0, "0000-00-00 00:00:00", 0, "0000-00-00 00:00:00", 0)'; $db->setQuery($q); $db->query(); $q = 'INSERT INTO `#__virtuemart_shipmentmethods_'.$lang.'` (`virtuemart_shipmentmethod_id`, `shipment_name`, `shipment_desc`, `slug`) VALUES (1, "Self pick-up", "", "Self-pick-up")'; $db->setQuery($q); $db->query(); //Create table of the plugin if(JVM_VERSION!=1){ $url = '/plugins/vmshipment/weight_countries'; } else{ $url = '/plugins/vmshipment'; } if (!class_exists ('plgVmShipmentWeight_countries')) require(JPATH_ROOT . DS . $url . DS . 'weight_countries.php'); $this->installPluginTable('plgVmShipmentWeight_countries','#__virtuemart_shipment_plg_weight_countries','Shipment Weight Countries Table'); } $q = 'SELECT `extension_id` FROM #__extensions WHERE element = "standard" AND folder = "vmpayment"'; $db->setQuery($q); $payment_plg_id = $db->loadResult(); if(!empty($payment_plg_id)){ $q='INSERT INTO `#__virtuemart_paymentmethods` (`virtuemart_paymentmethod_id`, `virtuemart_vendor_id`, `payment_jplugin_id`, `payment_element`, `payment_params`, `shared`, `ordering`, `published`, `created_on`, `created_by`, `modified_on`, `modified_by`, `locked_on`, `locked_by`) VALUES (1, 1, '.$payment_plg_id.', "standard", \'payment_logos=""|countries=""|payment_currency="0"|status_pending="U"|send_invoice_on_order_null="1"|min_amount=""|max_amount=""|cost_per_transaction="0.10"|cost_percent_total="1.5"|tax_id="0"|payment_info=""|\', 0, 0, 1, "0000-00-00 00:00:00", 0, "0000-00-00 00:00:00", 0, "0000-00-00 00:00:00", 0)'; $db->setQuery($q); $db->query(); $q="INSERT INTO `#__virtuemart_paymentmethods_".$lang."` (`virtuemart_paymentmethod_id`, `payment_name`, `payment_desc`, `slug`) VALUES (1, 'Cash on delivery', '', 'Cash-on-delivery')"; $db->setQuery($q); $db->query(); if(JVM_VERSION!=1){ $url = '/plugins/vmpayment/standard'; } else{ $url = '/plugins/vmpayment'; } if (!class_exists ('plgVmPaymentStandard')) require(JPATH_ROOT . DS . $url . DS . 'standard.php'); $this->installPluginTable('plgVmPaymentStandard','#__virtuemart_payment_plg_standard','Payment Standard Table'); } vmInfo(JText::_('COM_VIRTUEMART_SAMPLE_DATA_INSTALLED')); } return true; } function installPluginTable ($className,$tablename,$tableComment) { $query = "CREATE TABLE IF NOT EXISTS `" . $tablename . "` ("; if(!empty($tablesFields)){ foreach ($tablesFields as $fieldname => $fieldtype) { $query .= '`' . $fieldname . '` ' . $fieldtype . " , "; } } else { $SQLfields = call_user_func($className."::getTableSQLFields"); //$SQLfields = $className::getTableSQLFields (); // $loggablefields = $className::getTableSQLLoggablefields (); $loggablefields = call_user_func($className."::getTableSQLLoggablefields"); foreach ($SQLfields as $fieldname => $fieldtype) { $query .= '`' . $fieldname . '` ' . $fieldtype . " , "; } foreach ($loggablefields as $fieldname => $fieldtype) { $query .= '`' . $fieldname . '` ' . $fieldtype . ", "; } } $query .= " PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='" . $tableComment . "' AUTO_INCREMENT=1 ;"; $db = JFactory::getDBO(); $db->setQuery($query); if (!$db->query ()) { vmError ( $className.'::onStoreInstallPluginTable: ' . JText::_ ('COM_VIRTUEMART_SQL_ERROR') . ' ' . $db->stderr (TRUE)); } } function restoreSystemDefaults() { JPluginHelper::importPlugin('vmextended'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onVmSqlRemove', $this); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'uninstall_essential_data.sql'; $this->execSQLFile($filename); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'uninstall_required_data.sql'; $this->execSQLFile($filename); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'install.sql'; $this->execSQLFile($filename); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'install_essential_data.sql'; $this->execSQLFile($filename); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'install_required_data.sql'; $this->execSQLFile($filename); if(!class_exists('GenericTableUpdater')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'tableupdater.php'); $updater = new GenericTableUpdater(); $updater->createLanguageTables(); JPluginHelper::importPlugin('vmextended'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onVmSqlRestore', $this); } function restoreSystemTablesCompletly() { $this->removeAllVMTables(); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'install.sql'; $this->execSQLFile($filename); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'install_essential_data.sql'; $this->execSQLFile($filename); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'install_required_data.sql'; $this->execSQLFile($filename); if(!class_exists('GenericTableUpdater')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'tableupdater.php'); $updater = new GenericTableUpdater(); $updater->createLanguageTables(); JPluginHelper::importPlugin('vmextended'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onVmSqlRestore', $this); } /** * Parse a sql file executing each sql statement found. * * @author Max Milbers */ function execSQLFile($sqlfile ) { // Check that sql files exists before reading. Otherwise raise error for rollback if ( !file_exists($sqlfile) ) { vmError('No SQL file provided!'); return false; } if(!class_exists('VmConfig')){ require_once(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'config.php'); VmConfig::loadConfig(false,true); } if(!defined('VMLANG')){ $params = JComponentHelper::getParams('com_languages'); $lang = $params->get('site', 'en-GB');//use default joomla $lang = strtolower(strtr($lang,'-','_')); } else { $lang = VMLANG; } // Create an array of queries from the sql file jimport('joomla.installer.helper'); $queries = JInstallerHelper::splitSql(file_get_contents($sqlfile)); if (count($queries) == 0) { vmError('SQL file has no queries!'); return false; } $ok = true; $db = JFactory::getDBO(); // Process each query in the $queries array (split out of sql file). foreach ($queries as $query) { $query = trim($query); if ($query != '' && $query{0} != '#') { if(strpos($query, 'CREATE' )!==false or strpos( $query, 'INSERT')!==false){ $query = str_replace('XLANG',$lang,$query); } $db->setQuery($query); if (!$db->query()) { JError::raiseWarning(1, 'JInstaller::install: '.$sqlfile.' '.JText::_('COM_VIRTUEMART_SQL_ERROR')." ".$db->stderr(true)); $ok = false; } } } return $ok; } /** * Delete all Virtuemart tables. * * @return True if successful, false otherwise */ function removeAllVMTables() { $db = JFactory::getDBO(); $config = JFactory::getConfig(); $prefix = $config->getValue('config.dbprefix').'virtuemart_%'; $db->setQuery('SHOW TABLES LIKE "'.$prefix.'"'); if (!$tables = $db->loadResultArray()) { vmInfo ('removeAllVMTables no tables found '.$db->getErrorMsg()); return false; } $app = JFactory::getApplication(); foreach ($tables as $table) { $db->setQuery('DROP TABLE ' . $table); if($db->query()){ $droppedTables[] = substr($table,strlen($prefix)-1); } else { $errorTables[] = $table; $app->enqueueMessage('Error drop virtuemart table ' . $table); } } if(!empty($droppedTables)){ $app->enqueueMessage('Dropped virtuemart table ' . implode(', ',$droppedTables)); } if(!empty($errorTables)){ $app->enqueueMessage('Error dropping virtuemart table ' . implode($errorTables,', ')); return false; } return true; } /** * Remove all the data from all Virutmeart tables. * * @return boolean True if successful, false otherwise. */ function removeAllVMData() { JPluginHelper::importPlugin('vmextended'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onVmSqlRemove', $this); $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'uninstall_data.sql'; $this->execSQLFile($filename); $tables = array('categories','manufacturers','manufacturercategories','paymentmethods','products','shipmentmethods','vendors'); $prefix = $this->_db->getPrefix(); foreach ($tables as $table) { $query = 'SHOW TABLES LIKE "'.$prefix.'virtuemart_'.$table.'_%"'; $this->_db->setQuery($query); if($translatedTables= $this->_db->loadResultArray()) { foreach ($translatedTables as $translatedTable) { $this->_db->setQuery('TRUNCATE TABLE `'.$translatedTable.'`'); if($this->_db->query()) vmInfo( $translatedTable.' empty'); else vmError($translatedTable.' language table Cannot be deleted'); } } else vmInfo('No '.$table.' language table found to delete '.$query); } //"TRUNCATE TABLE IS FASTER and reset the primary Keys; //install required data again $filename = JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'install'.DS.'install_required_data.sql'; $this->execSQLFile($filename); return true; } /** * This function deletes all stored thumbs and deletes the entries for all thumbs, usually this is need for shops * older than vm2.0.22. The new pattern is now not storing the url as long it is not overwritten. * Of course the function deletes all overwrites, but you can now relativly easy change the thumbsize in your shop * @author Max Milbers */ function resetThumbs(){ $db = JFactory::getDbo(); $q = 'UPDATE `#__virtuemart_medias` SET `file_url_thumb`=""'; $db->setQuery($q); $db->query(); $err = $db->getErrorMsg(); if(!empty($err)){ vmError('resetThumbs Update entries failed ',$err); } jimport('joomla.filesystem.folder'); $tmpimg_resize_enable = VmConfig::get('img_resize_enable',1); VmConfig::set('img_resize_enable',0); $this->deleteMediaThumbFolder('media_category_path'); $this->deleteMediaThumbFolder('media_product_path'); $this->deleteMediaThumbFolder('media_manufacturer_path'); $this->deleteMediaThumbFolder('media_vendor_path'); $this->deleteMediaThumbFolder('forSale_path_thumb',''); VmConfig::set('img_resize_enable',$tmpimg_resize_enable); return true; } /** * Delets a thumb folder and recreates it, contains small nasty hack for the thumbnail folder of the "file for sale" * @author Max Milbers * @param $type * @param string $resized * @return bool */ private function deleteMediaThumbFolder($type,$resized='resized'){ if(!empty($resized)) $resized = DS.$resized; $typePath = VmConfig::get($type); if(!empty($typePath)){ $path = JPATH_ROOT.DS.str_replace('/',DS,$typePath).$resized; $msg = JFolder::delete($path); if(!$msg){ vmWarn('Problem deleting '.$type); } if(!class_exists('JFile')) require(JPATH_VM_LIBRARIES.DS.'joomla'.DS.'filesystem'.DS.'file.php'); $msg = JFolder::create($path); return $msg; } else { return 'Config path for '.$type.' empty'; } } } //pure php no tag ratings.php000066600000037414151372127700006746 0ustar00setMainTable('ratings'); $layout = JRequest::getString('layout','default'); $task = JRequest::getCmd('task','default'); if($layout == 'list_reviews' or $task == 'listreviews'){ vmdebug('in review list'); $myarray = array('pr.created_on','virtuemart_rating_review_id','vote'); $this->removevalidOrderingFieldName('created_on'); $this->removevalidOrderingFieldName('product_name'); $this->removevalidOrderingFieldName('virtuemart_rating_id'); $this->removevalidOrderingFieldName('rating'); $this->_selectedOrdering = 'pr.created_on'; } else { $myarray = array('created_on','product_name','virtuemart_rating_id'); $this->removevalidOrderingFieldName('pr.created_on'); $this->removevalidOrderingFieldName('virtuemart_rating_review_id'); $this->removevalidOrderingFieldName('vote'); $this->_selectedOrdering = 'created_on'; } $this->addvalidOrderingFieldName($myarray); } /** * Select the products to list on the product list page */ public function getRatings() { $tables = ' FROM `#__virtuemart_ratings` AS `r` JOIN `#__virtuemart_products_'.VMLANG.'` AS `p` USING (`virtuemart_product_id`) '; $whereString = ''; $this->_data = $this->exeSortSearchListQuery(0,' r.*,p.`product_name` ',$tables,$whereString,'',$this->_getOrdering()); // $this->_data = $this->_getList($q, $this->getState('limitstart'), $this->getState('limit')); // set total for pagination // $this->_total = $this->_getListCount($q) ; // if(empty($this->_data)) $this->_data = array(); // if(!isset($this->_total)) $this->_total = 0; return $this->_data; } /** * Load a single rating * @author RolandD */ public function getRating($cids) { if (empty($cids)) { return; } /* First copy the product in the product table */ $ratings_data = $this->getTable('ratings'); /* Load the rating */ $joinValue = array('product_name' =>'#__virtuemart_products'); if ($cids) { $ratings_data->load ($cids[0], $joinValue, 'virtuemart_product_id'); } /* Add some variables for a new rating */ if (JRequest::getWord('task') == 'add') { $virtuemart_product_id = JRequest::getVar('virtuemart_product_id',array(),'', 'array'); if(is_array($virtuemart_product_id) && count($virtuemart_product_id) > 0){ $virtuemart_product_id = (int)$virtuemart_product_id[0]; } else { $virtuemart_product_id = (int)$virtuemart_product_id; } $ratings_data->virtuemart_product_id = $virtuemart_product_id; /* User ID */ $user = JFactory::getUser(); $ratings_data->virtuemart_user_id = $user->id; } return $ratings_data; } /** * @author Max Milbers * @param $virtuemart_product_id * @return null */ function getReviews($virtuemart_product_id){ if (empty($virtuemart_product_id)) { return NULL; } $select = '`u`.*,`pr`.*,`p`.`product_name`,`rv`.`vote`, `u`.`name` AS customer, `pr`.`published`'; $tables = ' FROM `#__virtuemart_rating_reviews` AS `pr` LEFT JOIN `#__users` AS `u` ON `pr`.`created_by` = `u`.`id` LEFT JOIN `#__virtuemart_products_'.VMLANG.'` AS `p` ON `p`.`virtuemart_product_id` = `pr`.`virtuemart_product_id` LEFT JOIN `#__virtuemart_rating_votes` AS `rv` on `rv`.`virtuemart_product_id`=`pr`.`virtuemart_product_id` and `rv`.`created_by`=`u`.`id`'; $whereString = ' WHERE `p`.`virtuemart_product_id` = "'.$virtuemart_product_id.'"'; $result = $this->exeSortSearchListQuery(0,$select,$tables,$whereString,'',$this->_getOrdering()); return $result; } /** * @author Max Milbers * @param $cids * @return mixed@ */ function getReview($cids){ $q = 'SELECT `u`.*,`pr`.*,`p`.`product_name`,`rv`.`vote`,CONCAT_WS(" ",`u`.`title`,u.`last_name`,`u`.`first_name`) as customer FROM `#__virtuemart_rating_reviews` AS `pr` LEFT JOIN `#__virtuemart_userinfos` AS `u` ON `pr`.`created_by` = `u`.`virtuemart_user_id` LEFT JOIN `#__virtuemart_products_'.VMLANG.'` AS `p` ON `p`.`virtuemart_product_id` = `pr`.`virtuemart_product_id` LEFT JOIN `#__virtuemart_rating_votes` as `rv` on `rv`.`virtuemart_product_id`=`pr`.`virtuemart_product_id` and `rv`.`created_by`=`pr`.`created_by` WHERE virtuemart_rating_review_id="'.(int)$cids[0].'" ' ; $this->_db->setQuery($q); vmdebug('getReview',$this->_db->getQuery()); return $this->_db->loadObject(); } /** * gets a rating by a product id * * @author Max Milbers * @param int $product_id */ function getRatingByProduct($product_id){ $q = 'SELECT * FROM `#__virtuemart_ratings` WHERE `virtuemart_product_id` = "'.(int)$product_id.'" '; $this->_db->setQuery($q); return $this->_db->loadObject(); } /** * gets a review by a product id * * @author Max Milbers * @param int $product_id */ function getReviewByProduct($product_id,$userId=0){ if(empty($userId)){ $user = JFactory::getUser(); $userId = $user->id; } $q = 'SELECT * FROM `#__virtuemart_rating_reviews` WHERE `virtuemart_product_id` = "'.(int)$product_id.'" AND `created_by` = "'.(int)$userId.'" '; $this->_db->setQuery($q); return $this->_db->loadObject(); } /** * gets a reviews by a product id * * @author Max Milbers * @param int $product_id */ function getReviewsByProduct($product_id){ if(empty($userId)){ $user = JFactory::getUser(); $userId = $user->id; } $q = 'SELECT * FROM `#__virtuemart_rating_reviews` WHERE `virtuemart_product_id` = "'.(int)$product_id.'" '; $this->_db->setQuery($q); return $this->_db->loadObjectList(); } /** * gets a vote by a product id and userId * * @author Max Milbers * @param int $product_id */ function getVoteByProduct($product_id,$userId=0){ if(empty($userId)){ $user = JFactory::getUser(); $userId = $user->id; } $q = 'SELECT * FROM `#__virtuemart_rating_votes` WHERE `virtuemart_product_id` = "'.(int)$product_id.'" AND `created_by` = "'.(int)$userId.'" '; $this->_db->setQuery($q); return $this->_db->loadObject(); } /** * Save a rating * @author Max Milbers */ public function saveRating($data=0) { //Check user_rating $maxrating = VmConfig::get('vm_maximum_rating_scale',5); $virtuemart_product_id = vRequest::getInt('virtuemart_product_id',0); $app = JFactory::getApplication(); if( $app->isSite() ){ $user = JFactory::getUser(); $userId = $user->id; $allowReview = $this->allowReview($virtuemart_product_id); $allowRating = $this->allowRating($virtuemart_product_id); } else { $userId = $data['created_by']; $allowReview = true; $allowRating = true; } if(!empty($virtuemart_product_id)){ //if ( !empty($data['virtuemart_product_id']) && !empty($userId)){ if(empty($data)) $data = vRequest::getPost(); if($allowRating){ //normalize the rating if ($data['vote'] < 0) { $data['vote'] = 0; } if ($data['vote'] > ($maxrating + 1)) { $data['vote'] = $maxrating; } $data['lastip'] = $_SERVER['REMOTE_ADDR']; $data['vote'] = (int) $data['vote']; $rating = $this->getRatingByProduct($data['virtuemart_product_id']); vmdebug('$rating',$rating); $vote = $this->getVoteByProduct($data['virtuemart_product_id'],$userId); vmdebug('$vote',$vote); $data['virtuemart_rating_vote_id'] = empty($vote->virtuemart_rating_vote_id)? 0: $vote->virtuemart_rating_vote_id; if(isset($data['vote'])){ $votesTable = $this->getTable('rating_votes'); $votesTable->bindChecknStore($data,TRUE); $errors = $votesTable->getErrors(); foreach($errors as $error){ vmError(get_class( $this ).'::Error store votes '.$error); } } if(!empty($rating->rates) && empty($vote) ){ $data['rates'] = $rating->rates + $data['vote']; $data['ratingcount'] = $rating->ratingcount+1; } else { if (!empty($rating->rates) && !empty($vote->vote)) { $data['rates'] = $rating->rates - $vote->vote + $data['vote']; $data['ratingcount'] = $rating->ratingcount; } else { $data['rates'] = $data['vote']; $data['ratingcount'] = 1; } } if(empty($data['rates']) || empty($data['ratingcount']) ){ $data['rating'] = 0; } else { $data['rating'] = $data['rates']/$data['ratingcount']; } $data['virtuemart_rating_id'] = empty($rating->virtuemart_rating_id)? 0: $rating->virtuemart_rating_id; vmdebug('saveRating $data',$data); $rating = $this->getTable('ratings'); $rating->bindChecknStore($data,TRUE); $errors = $rating->getErrors(); foreach($errors as $error){ vmError(get_class( $this ).'::Error store rating '.$error); } } if($allowReview and !empty($data['comment'])){ //if(!empty($data['comment'])){ $data['comment'] = substr($data['comment'], 0, VmConfig::get('vm_reviews_maximum_comment_length', 2000)) ; // no HTML TAGS but permit all alphabet $value = preg_replace('@<[\/\!]*?[^<>]*?>@si','',$data['comment']);//remove all html tags $value = (string)preg_replace('#on[a-z](.+?)\)#si','',$value);//replace start of script onclick() onload()... $value = trim(str_replace('"', ' ', $value),"'") ; $data['comment'] = (string)preg_replace('#^\'#si','',$value);//replace ' at start $data['comment'] = nl2br($data['comment']); // keep returns //set to defaut value not used (prevent hack) $data['review_ok'] = 0; $data['review_rating'] = 0; $data['review_editable'] = 0; // Check if ratings are auto-published (set to 0 prevent injected by user) // $app = JFactory::getApplication(); if( $app->isSite() ){ if (!class_exists ('Permissions')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); } if(!Permissions::getInstance()->check('admin')){ if (VmConfig::get ('reviews_autopublish', 1)) { $data['published'] = 1; } } } $review = $this->getReviewByProduct($data['virtuemart_product_id'],$userId); if(!empty($review->review_rates)){ $data['review_rates'] = $review->review_rates + $data['vote']; } else { $data['review_rates'] = $data['vote']; } if(!empty($review->review_ratingcount)){ $data['review_ratingcount'] = $review->review_ratingcount+1; } else { $data['review_ratingcount'] = 1; } $data['review_rating'] = $data['review_rates']/$data['review_ratingcount']; $data['virtuemart_rating_review_id'] = empty($review->virtuemart_rating_review_id)? 0: $review->virtuemart_rating_review_id; $reviewTable = $this->getTable('rating_reviews'); $reviewTable->bindChecknStore($data,TRUE); $errors = $reviewTable->getErrors(); foreach($errors as $error){ vmError(get_class( $this ).'::Error store review '.$error); } } return $data['virtuemart_rating_review_id']; } else{ vmError('Cant save rating/review/vote without vote/product_id'); return FALSE; } } /** * removes a product and related table entries * * @author Max Milberes */ public function remove($ids) { $rating = $this->getTable($this->_maintablename); $review = $this->getTable('rating_reviews'); $votes = $this->getTable('rating_votes'); $ok = TRUE; foreach($ids as $id) { $rating->load($id); $prod_id = $rating->virtuemart_product_id; if (!$rating->delete($id)) { vmError(get_class( $this ).'::Error deleting ratings '.$rating->getError()); $ok = FALSE; } if (!$review->delete($prod_id,'virtuemart_product_id')) { vmError(get_class( $this ).'::Error deleting review '.$review->getError()); $ok = FALSE; } if (!$votes->delete($prod_id,'virtuemart_product_id')) { vmError(get_class( $this ).'::Error deleting votes '.$votes->getError()); $ok = FALSE; } } return $ok; } /** * Returns the number of reviews assigned to a product * * @author RolandD * @param int $pid Product ID * @return int */ public function countReviewsForProduct($pid) { $db = JFactory::getDBO(); $q = "SELECT COUNT(*) AS total FROM #__virtuemart_rating_reviews WHERE virtuemart_product_id=".(int)$pid; $db->setQuery($q); $reviews = $db->loadResult(); return $reviews; } public function showReview($product_id){ return $this->show($product_id, VmConfig::get('showReviewFor','all')); } public function showRating($product_id = 0){ return $this->show($product_id, VmConfig::get('showRatingFor','all')); } public function allowReview($product_id){ return $this->show($product_id, VmConfig::get('reviewMode','bought')); } public function allowRating($product_id){ return $this->show($product_id, VmConfig::get('ratingMode','bought')); } /** * Decides if the rating/review should be shown on the FE * @author Max Milbers */ private function show($product_id, $show){ //dont show if($show == 'none'){ return false; } //show all else { if ($show == 'all') { return true; } //show only registered else { if ($show == 'registered') { $user = JFactory::getUser (); return !empty($user->id); } //show only registered && who bought the product else { if ($show == 'bought') { if (empty($product_id)) { return false; } if (isset($this->_productBought[$product_id])) { return $this->_productBought[$product_id]; } $user = JFactory::getUser (); $rr_os=VmConfig::get('rr_os',array('C')); if(!is_array($rr_os)) $rr_os = array($rr_os); $db = JFactory::getDBO (); $q = 'SELECT COUNT(*) as total FROM `#__virtuemart_orders` AS o LEFT JOIN `#__virtuemart_order_items` AS oi '; $q .= 'ON `o`.`virtuemart_order_id` = `oi`.`virtuemart_order_id` '; $q .= 'WHERE o.virtuemart_user_id = "' . $user->id . '" AND oi.virtuemart_product_id = "' . $product_id . '" '; $q .= 'AND o.order_status IN (\'' . implode("','",$rr_os). '\') '; $db->setQuery ($q); $count = $db->loadResult (); if ($count) { $this->_productBought[$product_id] = true; return true; } else { $this->_productBought[$product_id] = false; return false; } } } } } } } // pure php no closing tag waitinglist.php000066600000011272151372127700007627 0ustar00setQuery ($q); return $db->loadObjectList (); } /** * Notify customers product is back in stock * * @author RolandD * @author Christopher Rouseel * @todo Add Itemid * @todo Do something if the mail cannot be send * @todo Update mail from * @todo Get the from name/email from the vendor */ public function notifyList ($virtuemart_product_id, $subject = '', $mailbody = '', $max_number = 0) { if (!$virtuemart_product_id) { return FALSE; } //sanitize id $virtuemart_product_id = (int)$virtuemart_product_id; $max_number = (int)$max_number; if (!class_exists ('shopFunctionsF')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'shopfunctionsf.php'); } $vars = array(); $waiting_users = $this->getWaitingusers ($virtuemart_product_id); /* Load the product details */ $db = JFactory::getDbo (); $q = "SELECT l.product_name,product_in_stock FROM `#__virtuemart_products_" . VMLANG . "` l JOIN `#__virtuemart_products` p ON p.virtuemart_product_id=l.virtuemart_product_id WHERE p.virtuemart_product_id = " . $virtuemart_product_id; $db->setQuery ($q); $item = $db->loadObject (); $vars['productName'] = $item->product_name; /* if ($item->product_in_stock <= 0) { return FALSE; } */ $url = JURI::root () . 'index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=' . $virtuemart_product_id; $vars['link'] = ''. $item->product_name.''; if (empty($subject)) { $subject = JText::sprintf('COM_VIRTUEMART_PRODUCT_WAITING_LIST_EMAIL_SUBJECT', $item->product_name); } $vars['subject'] = $subject; $vars['mailbody'] = $mailbody; $virtuemart_vendor_id = 1; $vendorModel = VmModel::getModel ('vendor'); $vendor = $vendorModel->getVendor ($virtuemart_vendor_id); $vendorModel->addImages ($vendor); $vars['vendor'] = $vendor; $vars['vendorAddress']= shopFunctions::renderVendorAddress($virtuemart_vendor_id); $vendorEmail = $vendorModel->getVendorEmail ($virtuemart_vendor_id); $vars['vendorEmail'] = $vendorEmail; $i = 0; foreach ($waiting_users as $waiting_user) { $vars['user'] = $waiting_user->name ; if (shopFunctionsF::renderMail ('productdetails', $waiting_user->notify_email, $vars, 'productdetails')) { $db->setQuery ('UPDATE #__virtuemart_waitingusers SET notified=1 WHERE virtuemart_waitinguser_id=' . $waiting_user->virtuemart_waitinguser_id); $db->query (); $i++; } if (!empty($max_number) && $i >= $max_number) { break; } } return TRUE; } /** * Add customer to the waiting list for specific product * * @author Seyi Awofadeju * @return insert_id if the save was successful, false otherwise. */ public function adduser ($data) { JRequest::checkToken () or jexit ('Invalid Token, in notify customer'); $field = $this->getTable ('waitingusers'); if (!$field->bind ($data)) { // Bind data vmError ($field->getError ()); return FALSE; } if (!$field->check ()) { // Perform data checks vmError ($field->getError ()); return FALSE; } $_id = $field->store (); if ($_id === FALSE) { // Write data to the DB vmError ($field->getError ()); return FALSE; } //jexit(); return $_id; } } // pure php no closing tag manufacturer.php000066600000013565151372127700007774 0ustar00setMainTable('manufacturers'); $this->addvalidOrderingFieldName(array('m.virtuemart_manufacturer_id','mf_name','mf_desc','mf_category_name','mf_url')); $this->removevalidOrderingFieldName('virtuemart_manufacturer_id'); $this->_selectedOrdering = 'mf_name'; $this->_selectedOrderingDir = 'ASC'; } /** * Load a single manufacturer */ public function getManufacturer() { static $_manus = array(); if (!array_key_exists ($this->_id, $_manus)) { $this->_data = $this->getTable('manufacturers'); $this->_data->load($this->_id); $xrefTable = $this->getTable('manufacturer_medias'); $this->_data->virtuemart_media_id = $xrefTable->load($this->_id); $_manus[$this->_id] = $this->_data; } return $_manus[$this->_id]; } /** * Bind the post data to the manufacturer table and save it * * @author Roland * @author Max Milbers * @return boolean True is the save was successful, false otherwise. */ public function store(&$data) { // Setup some place holders $table = $this->getTable('manufacturers'); $table->bindChecknStore($data); $errors = $table->getErrors(); foreach($errors as $error){ vmError($error); } // Process the images $mediaModel = VmModel::getModel('Media'); $mediaModel->storeMedia($data,'manufacturer'); $errors = $mediaModel->getErrors(); foreach($errors as $error){ vmError($error); } return $table->virtuemart_manufacturer_id; } /** * Returns a dropdown menu with manufacturers * @author Max Milbers * @return object List of manufacturer to build filter select box */ function getManufacturerDropDown() { $db = JFactory::getDBO(); $query = "SELECT `virtuemart_manufacturer_id` AS `value`, `mf_name` AS text, '' AS disable FROM `#__virtuemart_manufacturers_".VMLANG."` ORDER BY `mf_name` ASC"; $db->setQuery($query); $options = $db->loadObjectList(); array_unshift($options, JHTML::_('select.option', '0', '- '. JText::_('COM_VIRTUEMART_SELECT_MANUFACTURER') .' -' )); return $options; } /** * Retireve a list of countries from the database. * * @param string $onlyPuiblished True to only retreive the publish countries, false otherwise * @param string $noLimit True if no record count limit is used, false otherwise * @return object List of manufacturer objects */ public function getManufacturers($onlyPublished=false, $noLimit=false, $getMedia=false) { $this->_noLimit = $noLimit; $mainframe = JFactory::getApplication(); // $db = JFactory::getDBO(); $option = 'com_virtuemart'; $virtuemart_manufacturercategories_id = $mainframe->getUserStateFromRequest( $option.'virtuemart_manufacturercategories_id', 'virtuemart_manufacturercategories_id', 0, 'int' ); $search = $mainframe->getUserStateFromRequest( $option.'search', 'search', '', 'string' ); $where = array(); if ($virtuemart_manufacturercategories_id > 0) { $where[] .= ' `m`.`virtuemart_manufacturercategories_id` = '. $virtuemart_manufacturercategories_id; } if ( $search && $search != 'true') { $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; //$search = $this->_db->Quote($search, false); $where[] .= ' LOWER( `mf_name` ) LIKE '.$search; } if ($onlyPublished) { $where[] .= ' `m`.`published` = 1'; } $whereString = ''; if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where) ; $select = ' `m`.*,`#__virtuemart_manufacturers_'.VMLANG.'`.*, mc.`mf_category_name` '; $joinedTables = 'FROM `#__virtuemart_manufacturers_'.VMLANG.'` JOIN `#__virtuemart_manufacturers` as m USING (`virtuemart_manufacturer_id`) '; $joinedTables .= ' LEFT JOIN `#__virtuemart_manufacturercategories_'.VMLANG.'` AS mc on mc.`virtuemart_manufacturercategories_id`= `m`.`virtuemart_manufacturercategories_id` '; $groupBy=' '; if($getMedia){ $select .= ',mmex.virtuemart_media_id '; $joinedTables .= 'LEFT JOIN `#__virtuemart_manufacturer_medias` as mmex ON `m`.`virtuemart_manufacturer_id`= mmex.`virtuemart_manufacturer_id` '; $groupBy=' GROUP BY `m`.`virtuemart_manufacturer_id` '; } $whereString = ' '; if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where).' ' ; $ordering = $this->_getOrdering(); return $this->_data = $this->exeSortSearchListQuery(0,$select,$joinedTables,$whereString,$groupBy,$ordering ); } } // pure php no closing tagcalc.php000066600000027517151372127700006204 0ustar00 St.Kraft 2013-02-24 manufacturer relation added * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * @version $Id: calc.php 6396 2012-09-05 17:35:36Z Milbo $ */ if(!class_exists('VmModel'))require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmmodel.php'); class VirtueMartModelCalc extends VmModel { /** * Constructor for the calc model. * * The calc id is read and detmimined if it is an array of ids or just one single id. * * @author RickG */ public function __construct(){ parent::__construct(); $this->setMainTable('calcs'); $this->setToggleName('calc_shopper_published'); $this->setToggleName('calc_vendor_published'); $this->setToggleName('shared'); $this->addvalidOrderingFieldName(array('virtuemart_category_id','virtuemart_country_id','virtuemart_state_id','virtuemart_shoppergroup_id' ,'virtuemart_manufacturer_id' )); } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * * @author Max Milbers */ public function getCalc(){ if (empty($this->_data)) { if(empty($this->_db)) $this->_db = JFactory::getDBO(); $this->_data = $this->getTable('calcs'); $this->_data->load((int)$this->_id); $xrefTable = $this->getTable('calc_categories'); $this->_data->calc_categories = $xrefTable->load($this->_id); if ( $xrefTable->getError() ) { vmError(get_class( $this ).' calc_categories '.$xrefTable->getError()); } $xrefTable = $this->getTable('calc_shoppergroups'); $this->_data->virtuemart_shoppergroup_ids = $xrefTable->load($this->_id); if ( $xrefTable->getError() ) { vmError(get_class( $this ).' calc_shoppergroups '.$xrefTable->getError()); } $xrefTable = $this->getTable('calc_countries'); $this->_data->calc_countries = $xrefTable->load($this->_id); if ( $xrefTable->getError() ) { vmError(get_class( $this ).' calc_countries '.$xrefTable->getError()); } $xrefTable = $this->getTable('calc_states'); $this->_data->virtuemart_state_ids = $xrefTable->load($this->_id); if ( $xrefTable->getError() ) { vmError(get_class( $this ).' virtuemart_state_ids '.$xrefTable->getError()); } $xrefTable = $this->getTable('calc_manufacturers'); $this->_data->virtuemart_manufacturers = $xrefTable->load($this->_id); if ( $xrefTable->getError() ) { vmError(get_class( $this ).' calc_manufacturers '.$xrefTable->getError()); } JPluginHelper::importPlugin('vmcalculation'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('plgVmGetPluginInternalDataCalc',array(&$this->_data)); } // if($errs = $this->getErrors()){ // $app = JFactory::getApplication(); // foreach($errs as $err){ // $app->enqueueMessage($err); // } // } // vmdebug('my calc',$this->_data); return $this->_data; } /** * Retrieve a list of calculation rules from the database. * * @author Max Milbers * @param string $onlyPuiblished True to only retreive the published Calculation rules, false otherwise * @param string $noLimit True if no record count limit is used, false otherwise * @return object List of calculation rule objects */ public function getCalcs($onlyPublished=false, $noLimit=false, $search=false){ $where = array(); $this->_noLimit = $noLimit; // add filters if ($onlyPublished) $where[] = '`published` = 1'; if($search){ $db = JFactory::getDBO(); $search = '"%' . $db->getEscaped( $search, true ) . '%"' ; $where[] = ' `calc_name` LIKE '.$search.' OR `calc_descr` LIKE '.$search.' OR `calc_value` LIKE '.$search.' '; } $whereString= ''; if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where) ; $this->_data = $this->exeSortSearchListQuery(0,'*',' FROM `#__virtuemart_calcs`',$whereString,'',$this->_getOrdering()); if(!class_exists('shopfunctions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'shopfunctions.php'); foreach ($this->_data as $data){ /* Write the first 5 categories in the list */ $data->calcCategoriesList = shopfunctions::renderGuiList('virtuemart_category_id','#__virtuemart_calc_categories','virtuemart_calc_id',$data->virtuemart_calc_id,'category_name','#__virtuemart_categories','virtuemart_category_id','category'); /* Write the first 5 shoppergroups in the list */ $data->calcShoppersList = shopfunctions::renderGuiList('virtuemart_shoppergroup_id','#__virtuemart_calc_shoppergroups','virtuemart_calc_id',$data->virtuemart_calc_id,'shopper_group_name','#__virtuemart_shoppergroups','virtuemart_shoppergroup_id','shoppergroup',4,false); /* Write the first 5 countries in the list */ $data->calcCountriesList = shopfunctions::renderGuiList('virtuemart_country_id','#__virtuemart_calc_countries','virtuemart_calc_id',$data->virtuemart_calc_id,'country_name','#__virtuemart_countries','virtuemart_country_id','country',4,false); /* Write the first 5 states in the list */ $data->calcStatesList = shopfunctions::renderGuiList('virtuemart_state_id','#__virtuemart_calc_states','virtuemart_calc_id',$data->virtuemart_calc_id,'state_name','#__virtuemart_states','virtuemart_state_id','state',4,false); /* Write the first 5 manufacturers in the list */ $data->calcManufacturersList = shopfunctions::renderGuiList('virtuemart_manufacturer_id','#__virtuemart_calc_manufacturers','virtuemart_calc_id',$data->virtuemart_calc_id,'mf_name','#__virtuemart_manufacturers','virtuemart_manufacturer_id','manufacturer'); $query = 'SELECT `currency_name` FROM `#__virtuemart_currencies` WHERE `virtuemart_currency_id` = "'.(int)$data->calc_currency.'" '; $this->_db->setQuery($query); $data->currencyName = $this->_db->loadResult(); JPluginHelper::importPlugin('vmcalculation'); $dispatcher = JDispatcher::getInstance(); $error = $dispatcher->trigger('plgVmGetPluginInternalDataCalcList',array(&$data)); } return $this->_data; } /** * Bind the post data to the calculation table and save it * * @author Max Milbers * @return boolean True is the save was successful, false otherwise. */ public function store(&$data) { JRequest::checkToken() or jexit( 'Invalid Token, in store calc'); $table = $this->getTable('calcs'); // Convert selected dates to MySQL format for storing. $startDate = JFactory::getDate($data['publish_up']); $data['publish_up'] = $startDate->toMySQL(); // if ($data['publish_down'] == '' or $data['publish_down']==0){ if (empty($data['publish_down']) || trim($data['publish_down']) == JText::_('COM_VIRTUEMART_NEVER')){ if(empty($this->_db)) $this->_db = JFactory::getDBO(); $data['publish_down'] = $this->_db->getNullDate(); } else { $expireDate = JFactory::getDate($data['publish_down']); $data['publish_down'] = $expireDate->toMySQL(); } $table->bindChecknStore($data); if($table->getError()){ vmError('Calculation store '.$table->getError()); return false; } $xrefTable = $this->getTable('calc_categories'); $xrefTable->bindChecknStore($data); if($xrefTable->getError()){ vmError('Calculation store '.$xrefTable->getError()); } $xrefTable = $this->getTable('calc_shoppergroups'); $xrefTable->bindChecknStore($data); if($xrefTable->getError()){ vmError('Calculation store '.$xrefTable->getError()); } $xrefTable = $this->getTable('calc_countries'); $xrefTable->bindChecknStore($data); if($xrefTable->getError()){ vmError('Calculation store '.$xrefTable->getError()); } $xrefTable = $this->getTable('calc_states'); $xrefTable->bindChecknStore($data); if($xrefTable->getError()){ vmError('Calculation store '.$xrefTable->getError()); } $xrefTable = $this->getTable('calc_manufacturers'); $xrefTable->bindChecknStore($data); if($xrefTable->getError()){ vmError('Calculation store '.$xrefTable->getError()); } if (!class_exists('vmCalculationPlugin')) require(JPATH_VM_PLUGINS . DS . 'vmcalculationplugin.php'); JPluginHelper::importPlugin('vmcalculation'); $dispatcher = JDispatcher::getInstance(); $error = $dispatcher->trigger('plgVmStorePluginInternalDataCalc',array(&$data)); $errMsg = $this->_db->getErrorMsg(); $errs = $this->_db->getErrors(); if(!empty($errMsg)){ $errNum = $this->_db->getErrorNum(); vmError('SQL-Error: '.$errNum.' '.$errMsg.'
used query '.$this->_db->getQuery()); } if(!empty($errs)){ foreach($errs as $err){ if(!empty($err)) vmError('Calculation store '.$err); } } return $table->virtuemart_calc_id; } static function getRule($kind){ if (!is_array($kind)) $kind = array($kind); $db = JFactory::getDBO(); $nullDate = $db->getNullDate(); $now = JFactory::getDate()->toMySQL(); $q = 'SELECT * FROM `#__virtuemart_calcs` WHERE '; foreach ($kind as $field){ $q .= '`calc_kind`='.$db->Quote($field).' OR '; } $q=substr($q,0,-3); $q .= 'AND ( publish_up = "' . $db->getEscaped($nullDate) . '" OR publish_up <= "' . $db->getEscaped($now) . '" ) AND ( publish_down = "' . $db->getEscaped($nullDate) . '" OR publish_down >= "' . $db->getEscaped($now) . '" ) '; $db->setQuery($q); $data = $db->loadObjectList(); if (!$data) { $data = new stdClass(); } return $data; } /** * Delete all calcs selected * * @author Max Milbers * @param array $cids categories to remove * @return boolean if the item remove was successful */ public function remove($cids) { JRequest::checkToken() or jexit( 'Invalid Token, in remove category'); $table = $this->getTable($this->_maintablename); $cat = $this->getTable('calc_categories'); $sgrp = $this->getTable('calc_shoppergroups'); $countries = $this->getTable('calc_countries'); $states = $this->getTable('calc_states'); $manufacturers = $this->getTable('calc_manufacturers'); $ok = true; foreach($cids as $id) { $id = (int)$id; vmdebug('remove '.$id); if (!$table->delete($id)) { vmError(get_class( $this ).'::remove '.$id.' '.$table->getError()); $ok = false; } if (!$cat->delete($id)) { vmError(get_class( $this ).'::remove '.$id.' '.$cat->getError()); $ok = false; } if (!$sgrp->delete($id)) { vmError(get_class( $this ).'::remove '.$id.' '.$sgrp->getError()); $ok = false; } if (!$countries->delete($id)) { vmError(get_class( $this ).'::remove '.$id.' '.$countries->getError()); $ok = false; } if (!$states->delete($id)) { vmError(get_class( $this ).'::remove '.$id.' '.$states->getError()); $ok = false; } // Mod. St.Kraft 2013-02-24 if (!$manufacturers->delete($id)) { vmError(get_class( $this ).'::remove '.$id.' '.$manufacturers->getError()); $ok = false; } // if(!class_exists('vmPSPlugin')) require(JPATH_VM_PLUGINS.DS.'vmpsplugin.php'); JPluginHelper::importPlugin('vmcalculation'); $dispatcher = JDispatcher::getInstance(); $returnValues = $dispatcher->trigger('plgVmDeleteCalculationRow', array( $id)); } return $ok; } static function getTaxes() { return self::getRule(array('TAX','VatTax','TaxBill')); } static function getDiscounts(){ return self::getRule(array('DATax','DATaxBill','DBTax','DBTaxBill')); } static function getDBDiscounts() { return self::getRule(array('DBTax','DBTaxBill')); } static function getDADiscounts() { return self::getRule(array('DATax','DATaxBill')); } }coupon.php000066600000005547151372127700006604 0ustar00setMainTable('coupons'); } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * * @author RickG */ function getCoupon() { $db = JFactory::getDBO(); if (empty($this->_data)) { $this->_data = $this->getTable('coupons'); $this->_data->load((int)$this->_id); } if (!$this->_data) { $this->_data = new stdClass(); $this->_id = 0; $this->_data = null; } return $this->_data; } /** * Bind the post data to the coupon table and save it * * @author RickG, Oscar van Eijk * @return mixed False if the save was unsuccessful, the coupon ID otherwise. */ function store(&$data) { $table = $this->getTable('coupons'); //$data = JRequest::get('post'); $table->bindChecknStore($data); // Convert selected dates to MySQL format for storing. if ($data['coupon_start_date']) { $startDate = JFactory::getDate($data['coupon_start_date']); $data['coupon_start_date'] = $startDate->toMySQL(); } if ($data['coupon_expiry_date']) { $expireDate = JFactory::getDate($data['coupon_expiry_date']); $data['coupon_expiry_date'] = $expireDate->toMySQL(); } parent::store($data); return $table->virtuemart_coupon_id; } /** * Retireve a list of coupons from the database. * * @author RickG * @return object List of coupon objects */ function getCoupons() { $whereString = ''; // if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where) ; return $this->_data = $this->exeSortSearchListQuery(0,'*',' FROM `#__virtuemart_coupons`',$whereString,'',$this->_getOrdering()); } } // pure php no closing tagstate.php000066600000007763151372127700006423 0ustar00setMainTable('states'); $this->_selectedOrderingDir = 'ASC'; } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * * Renamed to getSingleState to avoid overwriting by jseros * * @author Max Milbers */ function getSingleState(){ if (empty($this->_data)) { $this->_data = $this->getTable('states'); $this->_data->load((int)$this->_id); } return $this->_data; } /** * Retireve a list of countries from the database. * * @author RickG, Max Milbers * @return object List of state objects */ public function getStates($countryId, $noLimit=false, $published = false) { $quer= 'SELECT * FROM `#__virtuemart_states` WHERE `virtuemart_country_id`= "'.(int)$countryId.'" '; if($published){ $quer .= 'AND `published`="1" '; } $quer .= 'ORDER BY `#__virtuemart_states`.`state_name`'; if ($noLimit) { $this->_data = $this->_getList($quer); } else { $this->_data = $this->_getList($quer, $this->getState('limitstart'), $this->getState('limit')); } if(count($this->_data) >0){ $this->_total = $this->_getListCount($quer); } return $this->_data; } /** * Tests if a state and country fits together and if they are published * * @author Max Milbers * @return String Attention, this function gives a 0=false back in case of success */ public static function testStateCountry($countryId,$stateId) { $countryId = (int)$countryId; $stateId = (int)$stateId; vmdebug('testStateCountry country '.$countryId.' $stateId '.$stateId); $db = JFactory::getDBO(); $q = 'SELECT * FROM `#__virtuemart_countries` WHERE `virtuemart_country_id`= "'.$countryId.'" AND `published`="1" '; $db->setQuery($q); if($db->loadResult()){ //Test if country has states $q = 'SELECT * FROM `#__virtuemart_states` WHERE `virtuemart_country_id`= "'.$countryId.'" AND `published`="1" '; $db->setQuery($q); if($res = $db->loadResult()){ vmdebug('testStateCountry country has states ',$res); //Test if virtuemart_state_id fits to virtuemart_country_id $q = 'SELECT * FROM `#__virtuemart_states` WHERE `virtuemart_country_id`= "'.$countryId.'" AND `virtuemart_state_id`="'.$stateId.'" and `published`="1"'; $db->setQuery($q); if($db->loadResult()){ return true; } else { //There is a country, but the state does not exist or is unlisted return false; } } else { vmdebug('testStateCountry country has no states listed'); //This country has no states listed return true; } } else { //The given country does not exist, this can happen, when no country was chosen, which maybe valid. return true; } } } // pure php no closing taginventory.php000066600000006370151372127700007331 0ustar00setMainTable('products'); $this->addvalidOrderingFieldName(array('product_name','product_sku','product_in_stock','product_price','product_weight','published')); } /** * Select the products to list on the product list page * @author Max Milbers */ public function getInventory() { $select = ' `#__virtuemart_products`.`virtuemart_product_id`, `#__virtuemart_products`.`product_parent_id`, `product_name`, `product_sku`, `product_in_stock`, `product_weight`, `published`, `product_price`'; $joinedTables = 'FROM `#__virtuemart_products` LEFT JOIN `#__virtuemart_product_prices` ON `#__virtuemart_products`.`virtuemart_product_id` = `#__virtuemart_product_prices`.`virtuemart_product_id` LEFT JOIN `#__virtuemart_shoppergroups` ON `#__virtuemart_product_prices`.`virtuemart_shoppergroup_id` = `#__virtuemart_shoppergroups`.`virtuemart_shoppergroup_id`'; return $this->_data = $this->exeSortSearchListQuery(0,$select,$joinedTables,$this->getInventoryFilter(),'',$this->_getOrdering()); } /** * Collect the filters for the query * @author RolandD * @author Max Milbers */ private function getInventoryFilter() { /* Check some filters */ $filters = array(); if ($search = JRequest::getVar('filter_inventory', false)){ $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; //$search = $this->_db->Quote($search, false); $filters[] = '`#__virtuemart_products`.`product_name` LIKE '.$search; } if (JRequest::getInt('stockfilter', 0) == 1){ $filters[] = '`#__virtuemart_products`.`product_in_stock` > 0'; } if ($catId = JRequest::getInt('virtuemart_category_id', 0) > 0){ $filters[] = '`#__virtuemart_categories`.`virtuemart_category_id` = '.$catId; } $filters[] = '(`#__virtuemart_shoppergroups`.`default` = 1 OR `#__virtuemart_shoppergroups`.`default` is NULL)'; return ' WHERE '.implode(' AND ', $filters).$this->_getOrdering(); } } // pure php no closing tagworldzones.php000066600000004325151372127700007500 0ustar00setMainTable('worldzones'); } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * * @author RickG */ function getShipmentZone() { $db = JFactory::getDBO(); if (empty($this->_data)) { $query = 'SELECT * '; $query .= 'FROM `#__virtuemart_worldzones` '; $query .= 'WHERE `virtuemart_worldzone_id` = ' . (int)$this->_id; $db->setQuery($query); $this->_data = $db->loadObject(); } if (!$this->_data) { $this->_data = new stdClass(); $this->_id = 0; $this->_data = null; } return $this->_data; } /** * Retrieve a list of zone ids and zone names for use in a HTML select list. * * @author RickG */ function getWorldZonesSelectList() { $db = JFactory::getDBO(); $query = 'SELECT `virtuemart_worldzone_id`, `zone_name` '; $query .= 'FROM `#__virtuemart_worldzones`'; $db->setQuery($query); return $db->loadObjectList(); } } // pure php no closing tagvendor.php000066600000031101151372127700006557 0ustar00setId (1); } $this->setMainTable ('vendors'); } /** * name: getLoggedVendor * Checks which $vendorId has the just logged in user. * * @author Max Milbers * @param @param $ownerOnly returns only an id if the vendorOwner is logged in (dont get confused with storeowner) * returns int $vendorId */ static function getLoggedVendor ($ownerOnly = TRUE) { $user = JFactory::getUser (); $userId = $user->id; if (isset($userId)) { $vendorId = self::getVendorId ('user', $userId, $ownerOnly); return $vendorId; } else { JError::raiseNotice (1, '$virtuemart_user_id empty, no user logged in'); return 0; } } /** * Retrieve the vendor details from the database. * * @author Max Milbers * @return object Vendor details */ function getVendor ($vendor_id = NULL) { if ($vendor_id) { $this->_id = $vendor_id; } if (empty($this->_data)) { $this->_data = $this->getTable ('vendors'); $this->_data->load ($this->_id); // vmdebug('getVendor',$this->_id,$this->_data); // Convert ; separated string into array if ($this->_data->vendor_accepted_currencies) { $this->_data->vendor_accepted_currencies = explode (',', $this->_data->vendor_accepted_currencies); } else { $this->_data->vendor_accepted_currencies = array(); } //Todo, check this construction $xrefTable = $this->getTable ('vendor_medias'); $this->_data->virtuemart_media_id = $xrefTable->load ($this->_id); } return $this->_data; } /** * Retrieve a list of vendors * todo only names are needed here, maybe it should be enhanced (loading object list is slow) * todo add possibility to load without limit * * @author RickG * @author Max Milbers * @return object List of vendors */ public function getVendors () { $this->setId (0); //This is important ! notice by Max Milbers $query = 'SELECT * FROM `#__virtuemart_vendors_' . VMLANG . '` as l JOIN `#__virtuemart_vendors` as v using (`virtuemart_vendor_id`)'; $query .= ' ORDER BY l.`virtuemart_vendor_id`'; $this->_data = $this->_getList ($query, $this->getState ('limitstart'), $this->getState ('limit')); return $this->_data; } /** * Find the user id given a vendor id * * @author Max Milbers * @param int $virtuemart_vendor_id * @return int $virtuemart_user_id */ static function getUserIdByVendorId ($vendorId) { //this function is used static, needs its own db if (empty($vendorId)) { return; } else { $db = JFactory::getDBO (); $query = 'SELECT `virtuemart_user_id` FROM `#__virtuemart_vmusers` WHERE `virtuemart_vendor_id`=' . (int)$vendorId; $db->setQuery ($query); $result = $db->loadResult (); $err = $db->getErrorMsg (); if (!empty($err)) { vmError ('getUserIdByVendorId ' . $err, 'Failed to retrieve user id by vendor'); } return (isset($result) ? $result : 0); } } /** * Bind the post data to the vendor table and save it * This function DOES NOT safe information which is in the vmusers or vm_user_info table * It only stores the stuff into the vendor table * * @author RickG * @author Max Milbers * @return boolean True is the save was successful, false otherwise. */ function store (&$data) { JPluginHelper::importPlugin ('vmvendor'); $dispatcher = JDispatcher::getInstance (); $plg_datas = $dispatcher->trigger ('plgVmOnVendorStore', $data); foreach ($plg_datas as $plg_data) { $data = array_merge ($plg_data); } $oldVendorId = $data['virtuemart_vendor_id']; $table = $this->getTable ('vendors'); /* if(!$table->checkDataContainsTableFields($data)){ $app = JFactory::getApplication(); //$app->enqueueMessage('Data contains no Info for vendor, storing not needed'); return $this->_id; }*/ // Store multiple selectlist entries as a ; separated string if (array_key_exists ('vendor_accepted_currencies', $data) && is_array ($data['vendor_accepted_currencies'])) { $data['vendor_accepted_currencies'] = implode (',', $data['vendor_accepted_currencies']); } $table->bindChecknStore ($data); $errors = $table->getErrors (); foreach ($errors as $error) { $this->setError ($error); vmError ('store vendor', $error); } //set vendormodel id to the lastinserted one // $dbv = $table->getDBO(); // if(empty($this->_id)) $this->_id = $dbv->insertid(); if (empty($this->_id)) { $data['virtuemart_vendor_id'] = $this->_id = $table->virtuemart_vendor_id; } if ($this->_id != $oldVendorId) { vmdebug('Developer notice, tried to update vendor xref should not appear in singlestore $oldVendorId = '.$oldVendorId.' newId = '.$this->_id); //update user table $usertable = $this->getTable ('vmusers'); // $vendorsUserData =$usertable->load($this->_id); // $vendorsUserData =$usertable->load($data['virtuemart_user_id']); // $vendorsUserData->virtuemart_vendor_id = $virtuemart_vendor_id; //$vmusersData = array('virtuemart_user_id'=>$data['virtuemart_user_id'],'user_is_vendor'=>1,'virtuemart_vendor_id'=>$virtuemart_vendor_id,'customer_number'=>$data['customer_number'],'perms'=>$data['perms']); $usertable->bindChecknStore ($data, TRUE); $errors = $usertable->getErrors (); foreach ($errors as $error) { $this->setError ($error); vmError ('Store vendor ' . $error); } } // Process the images $mediaModel = VmModel::getModel ('Media'); $mediaModel->storeMedia ($data, 'vendor'); $errors = $mediaModel->getErrors (); foreach ($errors as $error) { vmError ($error); } $plg_datas = $dispatcher->trigger ('plgVmAfterVendorStore', $data); foreach ($plg_datas as $plg_data) { $data = array_merge ($plg_data); } return $this->_id; } /** * Get the vendor specific currency * * @author Oscar van Eijk * @param $_vendorId Vendor ID * @return string Currency code */ static $_vendorCurrencies = array(); static function getVendorCurrency ($_vendorId) { if(!isset(self::$_vendorCurrencies[$_vendorId])){ $db = JFactory::getDBO (); $q = 'SELECT * FROM `#__virtuemart_currencies` AS c , `#__virtuemart_vendors` AS v WHERE v.virtuemart_vendor_id = ' . (int)$_vendorId . ' AND v.vendor_currency = c.virtuemart_currency_id'; $db->setQuery ($q); self::$_vendorCurrencies[$_vendorId] = $db->loadObject (); } return self::$_vendorCurrencies[$_vendorId]; } /** * Retrieve a lost of vendor objects * * @author Oscar van Eijk * @return Array with all Vendor objects */ function getVendorCategories () { $_q = 'SELECT * FROM `#__vm_vendor_category`'; $this->_db->setQuery ($_q); return $this->_db->loadObjectList (); } function getUserIdByOrderId ($virtuemart_order_id) { if (empty ($virtuemart_order_id)) { return 0; } $virtuemart_order_id = (int)$virtuemart_order_id; $q = "SELECT `virtuemart_user_id` FROM `#__virtuemart_orders` WHERE `virtuemart_order_id`='.$virtuemart_order_id'"; // $db->query( $q ); $this->_db->setQuery ($q); // if($db->next_record()){ if ($this->_db->query ()) { // $virtuemart_user_id = $db->f('virtuemart_user_id'); return $this->_db->loadResult (); } else { JError::raiseNotice (1, 'Error in DB $virtuemart_order_id ' . $virtuemart_order_id . ' dont have a virtuemart_user_id'); return 0; } } /** * Gets the vendorId by user Id mapped by table auth_user_vendor or by the order item * Assigned users cannot change storeinformations * ownerOnly = false should be used for users who are assigned to a vendor * for administrative jobs like execution of orders or managing products * Changing of vendorinformation should ONLY be possible by the Mainvendor who is in charge * * @author by Max Milbers * @author RolandD * @param string $type Where the vendor ID should be taken from * @param mixed $value Whatever value the vendor ID should be filtered on * @return int Vendor ID */ static public function getVendorId ($type, $value, $ownerOnly = TRUE) { if (empty($value)) { return 0; } //sanitize input params $value = (int)$value; //static call used, so we need our own db instance $db = JFactory::getDBO (); switch ($type) { case 'order': $q = 'SELECT virtuemart_vendor_id FROM #__virtuemart_order_items WHERE virtuemart_order_id=' . $value; break; case 'user': if ($ownerOnly) { $q = 'SELECT `virtuemart_vendor_id` FROM `#__virtuemart_vmusers` `au` LEFT JOIN `#__virtuemart_userinfos` `u` ON (au.virtuemart_user_id = u.virtuemart_user_id) WHERE `u`.`virtuemart_user_id`=' . $value; } else { $q = 'SELECT `virtuemart_vendor_id` FROM `#__virtuemart_vmusers` WHERE `virtuemart_user_id`= "' . $value . '" '; } break; case 'product': $q = 'SELECT virtuemart_vendor_id FROM #__virtuemart_products WHERE virtuemart_product_id=' . $value; break; } $db->setQuery ($q); $virtuemart_vendor_id = $db->loadResult (); if ($virtuemart_vendor_id) { return $virtuemart_vendor_id; } else { return 0; // if($type!='user'){ // return 0; // } else { // JError::raiseNotice(1, 'No virtuemart_vendor_id found for '.$value.' on '.$type.' check.'); // return 0; // } } } /** * This function gives back the storename for the given vendor. * * @author Max Milbers */ public function getVendorName ($virtuemart_vendor_id = 1) { $query = 'SELECT `vendor_store_name` FROM `#__virtuemart_vendors_' . VMLANG . '` WHERE `virtuemart_vendor_id` = "' . (int)$virtuemart_vendor_id . '" '; $this->_db->setQuery ($query); if ($this->_db->query ()) { return $this->_db->loadResult (); } else { return ''; } } /** * This function gives back the email for the given vendor. * * @author Max Milbers */ public function getVendorEmail ($virtuemart_vendor_id) { $virtuemart_user_id = self::getUserIdByVendorId ((int)$virtuemart_vendor_id); if (!empty($virtuemart_user_id)) { $query = 'SELECT `email` FROM `#__users` WHERE `id` = "' . $virtuemart_user_id . '" '; $this->_db->setQuery ($query); if ($this->_db->query ()) { return $this->_db->loadResult (); } else { return ''; } } return ''; } public function getVendorAdressBT ($virtuemart_vendor_id) { $userId = self::getUserIdByVendorId ($virtuemart_vendor_id); $usermodel = VmModel::getModel ('user'); // $usermodel->setId($userId); $virtuemart_userinfo_id = $usermodel->getBTuserinfo_id ($userId); $vendorAddressBt = $this->getTable ('userinfos'); $vendorAddressBt->load ($virtuemart_userinfo_id); return $vendorAddressBt; } private $_vendorFields = FALSE; public function getVendorAddressFields(){ if(!$this->_vendorFields){ $userId = VirtueMartModelVendor::getUserIdByVendorId ($this->_id); $userModel = VmModel::getModel ('user'); $virtuemart_userinfo_id = $userModel->getBTuserinfo_id ($userId); // this is needed to set the correct user id for the vendor when the user is logged $userModel->getVendor($this->_id,FALSE); $vendorFieldsArray = $userModel->getUserInfoInUserFields ('mail', 'BT', $virtuemart_userinfo_id, FALSE, TRUE); $this->_vendorFields = $vendorFieldsArray[$virtuemart_userinfo_id]; } return $this->_vendorFields; } } media.php000066600000034327151372127700006356 0ustar00setMainTable('medias'); $this->addvalidOrderingFieldName(array('ordering')); $this->_selectedOrdering = 'created_on'; } /** * Gets a single media by virtuemart_media_id * . * @param string $type * @param string $mime mime type of file, use for exampel image * @return mediaobject */ function getFile($type=0,$mime=0){ if (empty($this->_data)) { $data = $this->getTable('medias'); $data->load((int)$this->_id); if (!class_exists('VmMediaHandler')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'mediahandler.php'); $this->_data = VmMediaHandler::createMedia($data,$type,$mime); } return $this->_data; } /** * Kind of getFiles, it creates a bunch of image objects by an array of virtuemart_media_id * * @author Max Milbers * @param int $virtuemart_media_id * @param string $type * @param string $mime */ function createMediaByIds($virtuemart_media_ids,$type='',$mime='',$limit =0){ if (!class_exists('VmMediaHandler')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'mediahandler.php'); $app = JFactory::getApplication(); $medias = array(); static $_medias = array(); if(!empty($virtuemart_media_ids)){ if(!is_array($virtuemart_media_ids)) $virtuemart_media_ids = explode(',',$virtuemart_media_ids); //Lets delete empty ids //$virtuemart_media_ids = array_diff($virtuemart_media_ids,array('0','')); $data = $this->getTable('medias'); foreach($virtuemart_media_ids as $k => $virtuemart_media_id){ if($limit!==0 and $k==$limit and !empty($medias)) break; // never break if $limit = 0 if(is_object($virtuemart_media_id)){ $id = $virtuemart_media_id->virtuemart_media_id; } else { $id = $virtuemart_media_id; } if(!empty($id)){ if (!array_key_exists ($id, $_medias)) { $data->load((int)$id); if($app->isSite()){ if($data->published==0){ $_medias[$id] = $this->createVoidMedia($type,$mime); continue; } } $file_type = empty($data->file_type)? $type:$data->file_type; $mime = empty($data->file_mimetype)? $mime:$data->file_mimetype; if($app->isSite()){ $selectedLangue = explode(",", $data->file_lang); //vmdebug('selectedLangue',$selectedLangue); $lang = JFactory::getLanguage(); if(in_array($lang->getTag(), $selectedLangue) || $data->file_lang == '') { $_medias[$id] = VmMediaHandler::createMedia($data,$file_type,$mime); if(is_object($virtuemart_media_id) && !empty($virtuemart_media_id->product_name)) $_medias[$id]->product_name = $virtuemart_media_id->product_name; } } else { $_medias[$id] = VmMediaHandler::createMedia($data,$file_type,$mime); if(is_object($virtuemart_media_id) && !empty($virtuemart_media_id->product_name)) $_medias[$id]->product_name = $virtuemart_media_id->product_name; } } if (!empty($_medias[$id])) { $medias[] = $_medias[$id]; } } } } if(empty($medias)){ $medias[] = $this->createVoidMedia($type,$mime); } return $medias; } function createVoidMedia($type,$mime){ static $voidMedia = null; if(empty($voidMedia)){ $data = $this->getTable('medias'); //Create empty data $data->virtuemart_media_id = 0; $data->virtuemart_vendor_id = 0; $data->file_title = ''; $data->file_description = ''; $data->file_meta = ''; $data->file_mimetype = ''; $data->file_type = ''; $data->file_url = ''; $data->file_url_thumb = ''; $data->published = 0; $data->file_is_downloadable = 0; $data->file_is_forSale = 0; $data->file_is_product_image = 0; $data->shared = 0; $data->file_params = 0; $data->file_lang = ''; $voidMedia = VmMediaHandler::createMedia($data,$type,$mime); } return $voidMedia; } /** * Retrieve a list of files from the database. This is meant only for backend use * * @author Max Milbers * @param boolean $onlyPublished True to only retrieve the published files, false otherwise * @param boolean $noLimit True if no record count limit is used, false otherwise * @return object List of media objects */ function getFiles($onlyPublished=false, $noLimit=false, $virtuemart_product_id=null, $cat_id=null, $where=array(),$nbr=false){ $this->_noLimit = $noLimit; if(empty($this->_db)) $this->_db = JFactory::getDBO(); $vendorId = 1; //TODO set to logged user or requested vendorId, not easy later $query = ''; $selectFields = array(); $joinTables = array(); $joinedTables = ''; $whereItems= array(); $groupBy =''; $orderByTable = ''; if(!empty($virtuemart_product_id)){ $mainTable = '`#__virtuemart_product_medias`'; $selectFields[] = ' `#__virtuemart_medias`.`virtuemart_media_id` as virtuemart_media_id '; $joinTables[] = ' LEFT JOIN `#__virtuemart_medias` ON `#__virtuemart_medias`.`virtuemart_media_id`=`#__virtuemart_product_medias`.`virtuemart_media_id` and `virtuemart_product_id` = "'.$virtuemart_product_id.'"'; $whereItems[] = '`virtuemart_product_id` = "'.$virtuemart_product_id.'"'; if($this->_selectedOrdering=='ordering'){ $orderByTable = '`#__virtuemart_product_medias`.'; } else{ $orderByTable = '`#__virtuemart_medias`.'; } } else if(!empty($cat_id)){ $mainTable = '`#__virtuemart_category_medias`'; $selectFields[] = ' `#__virtuemart_medias`.`virtuemart_media_id` as virtuemart_media_id'; $joinTables[] = ' LEFT JOIN `#__virtuemart_medias` ON `#__virtuemart_medias`.`virtuemart_media_id`=`#__virtuemart_category_medias`.`virtuemart_media_id` and `virtuemart_category_id` = "'.$cat_id.'"'; $whereItems[] = '`virtuemart_category_id` = "'.$cat_id.'"'; if($this->_selectedOrdering=='ordering'){ $orderByTable = '`#__virtuemart_category_medias`.'; } else{ $orderByTable = '`#__virtuemart_medias`.'; } } else { $mainTable = '`#__virtuemart_medias`'; $selectFields[] = ' `virtuemart_media_id` '; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check('admin') ){ $whereItems[] = '(`virtuemart_vendor_id` = "'.(int)$vendorId.'" OR `shared`="1")'; } } if ($onlyPublished) { $whereItems[] = '`#__virtuemart_medias`.`published` = 1'; } if ($search = JRequest::getString('searchMedia', false)){ $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; $where[] = ' (`file_title` LIKE '.$search.' OR `file_description` LIKE '.$search.' OR `file_meta` LIKE '.$search.' OR `file_url` LIKE '.$search.' OR `file_url_thumb` LIKE '.$search.' ) '; } if ($type = JRequest::getWord('search_type')) { $where[] = 'file_type = "'.$type.'" ' ; } if ($role = JRequest::getWord('search_role')) { if ($role == "file_is_downloadable") { $where[] = '`file_is_downloadable` = 1'; $where[] = '`file_is_forSale` = 0'; } elseif ($role == "file_is_forSale") { $where[] = '`file_is_downloadable` = 0'; $where[] = '`file_is_forSale` = 1'; } else { $where[] = '`file_is_downloadable` = 0'; $where[] = '`file_is_forSale` = 0'; } } if (!empty($where)) $whereItems = array_merge($whereItems,$where); if(count($whereItems)>0){ $whereString = ' WHERE '.implode(' AND ', $whereItems ); } else { $whereString = ' '; } $orderBy = $this->_getOrdering($orderByTable);# if(count($selectFields)>0){ $select = implode(', ', $selectFields ).' FROM '.$mainTable; //$selectFindRows = 'SELECT COUNT(*) FROM '.$mainTable; if(count($joinTables)>0){ foreach($joinTables as $table){ $joinedTables .= $table; } } } else { vmError('No select fields given in getFiles','No select fields given'); return false; } $this->_data = $this->exeSortSearchListQuery(2, $select, $joinedTables, $whereString, $groupBy, $orderBy,'',$nbr); if(empty($this->_data)){ return array(); } if( !is_array($this->_data)){ $this->_data = explode(',',$this->_data); } $this->_data = $this->createMediaByIds($this->_data); return $this->_data; } /** * This function stores a media and updates then the refered table * * @author Max Milbers * @author Patrick Kohl * @param array $data Data from a from * @param string $type type of the media category,product,manufacturer,shop, ... */ function storeMedia($data,$type){ // vmdebug('my data in media to store start',$data['virtuemart_media_id']); JRequest::checkToken() or jexit( 'Invalid Token, while trying to save media' ); if(empty($data['media_action'])){ $data['media_action'] = 'none'; } //vmdebug('storeMedia',$data); //the active media id is not empty, so there should be something done with it //if( (!empty($data['active_media_id']) && !empty($data['virtuemart_media_id']) ) || $data['media_action']=='upload'){ if( (!empty($data['active_media_id']) and isset($data['virtuemart_media_id']) ) || $data['media_action']=='upload'){ $oldIds = $data['virtuemart_media_id']; $data['file_type'] = $type; //$data['virtuemart_media_id'] = (int)$data['active_media_id']; //done within the function now $this -> setId($data['active_media_id']); $virtuemart_media_id = $this->store($data,$type); //added by Mike, Mike why did you add this? This function storeMedia is extremely nasty $this->setId($virtuemart_media_id); if(!empty($oldIds)){ if(!is_array($oldIds)) $oldIds = array($oldIds); if(!empty($data['mediaordering']) && $data['media_action']=='upload'){ // array_push($data['mediaordering'],count($data['mediaordering'])+1); $data['mediaordering'][$virtuemart_media_id] = count($data['mediaordering']); } $virtuemart_media_ids = array_merge( (array)$virtuemart_media_id,$oldIds); // vmdebug('merged old and new',$virtuemart_media_ids); $data['virtuemart_media_id'] = array_unique($virtuemart_media_ids); } else { $data['virtuemart_media_id'] = $virtuemart_media_id; } } if(!empty($data['mediaordering'])){ asort($data['mediaordering']); $sortedMediaIds = array(); foreach($data['mediaordering'] as $k=>$v){ $sortedMediaIds[] = $k; } // vmdebug('merging old and new',$oldIds,$virtuemart_media_id); $data['virtuemart_media_id'] = $sortedMediaIds; } // vmdebug('my data in media to store',$data['virtuemart_media_id'],$data['mediaordering']); //set the relations $table = $this->getTable($type.'_medias'); // Bind the form fields to the country table $table->bindChecknStore($data); $errors = $table->getErrors(); foreach($errors as $error){ vmError($error); } return $table->virtuemart_media_id; } /** * Store an entry of a mediaItem, this means in end effect every media file in the shop * images, videos, pdf, zips, exe, ... * * @author Max Milbers */ public function store(&$data,$type) { VmConfig::loadJLang('com_virtuemart_media'); //if(empty($data['media_action'])) return $table->virtuemart_media_id; if (!class_exists('VmMediaHandler')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'mediahandler.php'); $table = $this->getTable('medias'); /* $a = trim($data['file_url_thumb']); $b = trim(JText::sprintf('COM_VIRTUEMART_DEFAULT_URL',$data['file_url_thumb'])); vmdebug(' the miese Assi',$a,$b); if( $a == $b ){ vmdebug('Unset the miese Assi'); unset($data['file_url_thumb']); }*/ //unset($data['file_url_thumb']); $data['virtuemart_media_id'] = $this->getId(); $table->bind($data); $data = VmMediaHandler::prepareStoreMedia($table,$data,$type); //this does not store the media, it process the actions and prepares data // workarround for media published and product published two fields in one form. $tmpPublished = false; if (isset($data['media_published'])){ $tmpPublished = $data['published']; $data['published'] = $data['media_published']; //vmdebug('$data["published"]',$data['published']); } $table->bindChecknStore($data); $errors = $table->getErrors(); foreach($errors as $error){ vmError('store medias '.$error); } if($tmpPublished){ $data['published'] = $tmpPublished; } // vmdebug('store media $table->virtuemart_media_id '.$table->virtuemart_media_id); return $table->virtuemart_media_id; } public function attachImages($objects,$type,$mime='',$limit=0){ if(!empty($objects)){ if(!is_array($objects)) $objects = array($objects); foreach($objects as $k => $object){ if(empty($object->virtuemart_media_id)) $virtuemart_media_id = null; else $virtuemart_media_id = $object->virtuemart_media_id; $object->images = $this->createMediaByIds($virtuemart_media_id,$type,$mime,$limit); //This should not be used in fact. It is for legacy reasons there. if(isset($object->images[0]->file_url_thumb)){ $object->file_url_thumb = $object->images[0]->file_url_thumb; $object->file_url = $object->images[0]->file_url; } } } } } // pure php no closing tag manufacturercategories.php000066600000010421151372127700012026 0ustar00setMainTable('manufacturercategories'); $this->addvalidOrderingFieldName(array('mf_category_name')); $config=JFactory::getConfig(); } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * */ // function getManufacturerCategory(){ //// $db = JFactory::getDBO(); // if (empty($this->_data)) { // $this->_data = $this->getTable('manufacturercategories'); // $this->_data->load((int)$this->_id); // } //// print_r( $this->_db->_sql ); // if (!$this->_data) { // $this->_data = new stdClass(); // $this->_id = 0; // $this->_data = null; // } // return $this->_data; // } /** * Delete all record ids selected * * @return boolean True is the remove was successful, false otherwise. */ function remove($categoryIds) { $table = $this->getTable('manufacturercategories'); foreach($categoryIds as $categoryId) { if($table->checkManufacturer($categoryId)) { if (!$table->delete($categoryId)) { vmError($table->getError()); return false; } } else { vmError(get_class( $this ).'::remove '.$categoryId.' '.$table->getError()); return false; } } return true; } /** * Retireve a list of countries from the database. * * @param string $onlyPuiblished True to only retreive the published categories, false otherwise * @param string $noLimit True if no record count limit is used, false otherwise * @return object List of manufacturer categories objects */ function getManufacturerCategories($onlyPublished=false, $noLimit=false) { $this->_noLimit = $noLimit; $select = '* FROM `#__virtuemart_manufacturercategories_'.VMLANG.'` as l'; $joinedTables = ' JOIN `#__virtuemart_manufacturercategories` as mc using (`virtuemart_manufacturercategories_id`)'; $where = array(); if ($onlyPublished) { $where[] = ' `#__virtuemart_manufacturercategories`.`published` = 1'; } // $query .= ' ORDER BY `#__virtuemart_manufacturercategories`.`mf_category_name`'; $whereString = ''; if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where) ; if ( JRequest::getCmd('view') == 'manufacturercategories') { $ordering = $this->_getOrdering(); } else { $ordering = ' order by mf_category_name DESC'; } return $this->_data = $this->exeSortSearchListQuery(0,$select,$whereString,$joinedTables,$ordering); } /** * Build category filter * * @return object List of category to build filter select box */ function getCategoryFilter(){ $db = JFactory::getDBO(); $query = 'SELECT `virtuemart_manufacturercategories_id` as `value`, `mf_category_name` as text' .' FROM #__virtuemart_manufacturercategories_'.VMLANG.'`'; $db->setQuery($query); $categoryFilter[] = JHTML::_('select.option', '0', '- '. JText::_('COM_VIRTUEMART_SELECT_MANUFACTURER_CATEGORY') .' -' ); $categoryFilter = array_merge($categoryFilter, (array)$db->loadObjectList()); return $categoryFilter; } } // pure php no closing tagcustom.php000066600000021072151372127700006602 0ustar00setMainTable('customs'); $this->setToggleName('admin_only'); $this->setToggleName('is_hidden'); } /** * Gets a single custom by virtuemart_custom_id * . * @param string $type * @param string $mime mime type of custom, use for exampel image * @return customobject */ function getCustom(){ if(empty($this->_data)){ // JTable::addIncludePath(JPATH_VM_ADMINISTRATOR.DS.'tables'); $this->_data = $this->getTable('customs'); $this->_data->load($this->_id); $customfields = VmModel::getModel('Customfields'); $this->_data->field_types = $customfields->getField_types() ; // vmdebug('getCustom $data',$this->_data); if(!empty($this->_data->custom_jplugin_id)){ JPluginHelper::importPlugin('vmcustom'); $dispatcher = JDispatcher::getInstance(); // $varsToPushParam = $dispatcher->trigger('plgVmDeclarePluginParams',array('custom',$this->_data->custom_element,$this->_data->custom_jplugin_id)); $retValue = $dispatcher->trigger('plgVmDeclarePluginParamsCustom',array('custom',$this->_data->custom_element,$this->_data->custom_jplugin_id,&$this->_data)); } else { //Todo this is not working, because the custom is using custom_params, while the customfield is using custom_param ! //VirtueMartModelCustomfields::bindParameterableByFieldType($this->_data); } } return $this->_data; } /** * Retireve a list of customs from the database. This is meant only for backend use * * @author Kohl Patrick, Max Milbers * @return object List of custom objects */ function getCustoms($custom_parent_id,$search = false){ $query='* FROM `#__virtuemart_customs` WHERE field_type <> "R" AND field_type <> "Z" AND field_type <> "G" '; if($custom_parent_id){ $query .= 'AND `custom_parent_id` ='.(int)$custom_parent_id; } if($search){ $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; $query .= 'AND `custom_title` LIKE '.$search; } $datas = new stdClass(); $datas->items = $this->exeSortSearchListQuery(0, $query, '','',$this->_getOrdering()); $customfields = VmModel::getModel('Customfields'); if (!class_exists('VmHTML')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'html.php'); $datas->field_types = $customfields->getField_types() ; foreach ($datas->items as $key => & $data) { if (!empty($data->custom_parent_id)) $data->custom_parent_title = $customfields->getCustomParentTitle($data->custom_parent_id); else { $data->custom_parent_title = '-' ; } if(!empty($datas->field_types[$data->field_type ])){ $data->field_type_display = vmText::_( $datas->field_types[$data->field_type ] ); } else { $data->field_type_display = 'not valid, delete this line'; vmError('The field with id '.$data->virtuemart_custom_id.' and title '.$data->custom_title.' is not longer valid, please delete it from the list'); } } $datas->customsSelect=$customfields->displayCustomSelection(); return $datas; } /** * Creates a clone of a given custom id * * @author Max Milbers * @param int $virtuemart_product_id */ public function createClone($id){ $this->virtuemart_custom_id = $id; $row = $this->getTable('customs'); $row->load( $id ); $row->virtuemart_custom_id = 0; $row->custom_title = $row->custom_title.' Copy'; if (!$clone = $row->store()) { JError::raiseError(500, 'createClone '. $row->getError() ); } return $clone; } /* Save and delete from database * all Child product custom_fields relation * @ var $table : the xref table(eg. product,category ...) * @array $data : array of customfields * @int $id : The concerned id (eg. product_id) **/ public function saveChildCustomRelation($table,$datas) { JRequest::checkToken() or jexit( 'Invalid Token, in store customfields'); //Table whitelist $tableWhiteList = array('product','category','manufacturer'); if(!in_array($table,$tableWhiteList)) return false; $customfieldIds = array(); // delete existings from modelXref and table customfields foreach ($datas as $child_id =>$fields) { $fields['virtuemart_'.$table.'_id']=$child_id; $this->_db->setQuery( 'DELETE PC FROM `#__virtuemart_'.$table.'_customfields` as `PC`, `#__virtuemart_customs` as `C` WHERE `PC`.`virtuemart_custom_id` = `C`.`virtuemart_custom_id` AND field_type="C" and virtuemart_'.$table.'_id ='.$child_id ); if(!$this->_db->query()){ vmError('Error in deleting child relation '); //.$this->_db->getQuery()); Dont give hackers too much info } $tableCustomfields = $this->getTable($table.'_customfields'); $tableCustomfields->bindChecknStore($fields); $errors = $tableCustomfields->getErrors(); foreach($errors as $error){ vmError($error); } } } public function store(&$data){ if(!empty($data['params'])){ foreach($data['params'] as $k=>$v){ $data[$k] = $v; } } if(empty($data['virtuemart_vendor_id'])){ if(!class_exists('VirtueMartModelVendor')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php'); $data['virtuemart_vendor_id'] = VirtueMartModelVendor::getLoggedVendor(); } else { $data['virtuemart_vendor_id'] = (int) $data['virtuemart_vendor_id']; } // missing string FIX, Bad way ? if (JVM_VERSION===1) { $tb = '#__plugins'; $ext_id = 'id'; } else { $tb = '#__extensions'; $ext_id = 'extension_id'; } $q = 'SELECT `element` FROM `' . $tb . '` WHERE `' . $ext_id . '` = "'.$data['custom_jplugin_id'].'"'; $this->_db->setQuery($q); $data['custom_element'] = $this->_db->loadResult(); // vmdebug('store custom',$data); $table = $this->getTable('customs'); if(isset($data['custom_jplugin_id'])){ vmdebug('$data store custom',$data); JPluginHelper::importPlugin('vmcustom'); $dispatcher = JDispatcher::getInstance(); // $retValue = $dispatcher->trigger('plgVmSetOnTablePluginParamsCustom',array($data['custom_value'],$data['custom_jplugin_id'],&$table)); $retValue = $dispatcher->trigger('plgVmSetOnTablePluginParamsCustom',array($data['custom_element'],$data['custom_jplugin_id'],&$table)); } $table->bindChecknStore($data); $errors = $table->getErrors(); if(!empty($errors)){ foreach($errors as $error){ vmError($error); } } JPluginHelper::importPlugin('vmcustom'); $dispatcher = JDispatcher::getInstance(); $error = $dispatcher->trigger('plgVmOnStoreInstallPluginTable', array('custom' , $data, $data['custom_element'])); return $table->virtuemart_custom_id ; } /** * Delete all record ids selected * * @author Max Milbers * @return boolean True is the delete was successful, false otherwise. */ public function remove($ids) { $table = $this->getTable($this->_maintablename); $customfields = $this->getTable ('product_customfields'); foreach($ids as $id) { if (!$table->delete((int)$id)) { vmError(get_class( $this ).'::remove '.$id.' '.$table->getError()); return false; } else { //Delete this customfield also in all product_customfield tables if (!$customfields->delete ($id, 'virtuemart_custom_id')) { vmError ('Custom delete Productcustomfield delete ' . $customfields->getError ()); $ok = FALSE; } } } return true; } } // pure php no closing tag orderstatus.php000066600000007211151372127700007646 0ustar00setMainTable('orderstates'); } function getVMCoreStatusCode(){ return array( 'P','S'); } /** * Retrieve a list of order statuses from the database. * * @return object List of order status objects */ function getOrderStatusList() { if (JRequest::getWord('view') !== 'orderstatus') $ordering = ' order by `ordering` '; else $ordering = $this->_getOrdering(); $this->_noLimit=true; $this->_data = $this->exeSortSearchListQuery(0,'*',' FROM `#__virtuemart_orderstates`','','',$ordering); // vmdebug('order data',$this->_data); return $this->_data ; } /** * Return the order status names * * @author Kohl Patrick * @access public * * @param char $_code Order status code * @return string The name of the order status */ public function getOrderStatusNames () { $q = 'SELECT `order_status_name`,`order_status_code` FROM `#__virtuemart_orderstates` order by `ordering` '; $this->_db->setQuery($q); return $this->_db->loadAssocList('order_status_code'); } function renderOSList($value,$name = 'order_status',$multiple=FALSE,$attrs='',$langkey='' ){ $idA = $id = $name; $attrs .= ' class="inputbox" '; if ($multiple) { $attrs .= ' multiple="multiple" '; if(empty($langkey)) $langkey = 'COM_VIRTUEMART_DRDOWN_SELECT_SOME_OPTIONS'; $attrs .= ' data-placeholder="'.JText::_($langkey).'"'; $idA .= '[]'; } else { if(empty($langkey)) $langkey = 'COM_VIRTUEMART_LIST_EMPTY_OPTION'; } if(is_array($value)){ $hashValue = implode($value); } else { $hashValue = $value; } $hash = md5($hashValue.$name.$attrs); if (!isset($this->_renderStatusList[$hash])) { $orderStates = $this->getOrderStatusNames(); $emptyOption = JHTML::_ ('select.option', -1, JText::_ ($langkey), 'order_status_code', 'order_status_name'); array_unshift ($orderStates, $emptyOption); if ($multiple) { $attrs .=' size="'.count($orderStates).'" '; } $this->_renderStatusList[$hash] = JHTML::_('select.genericlist', $orderStates, $idA, $attrs, 'order_status_code', 'order_status_name', $value,$id,true); } return $this->_renderStatusList[$hash] ; } function renderOrderStatusList($value, $name = 'order_status[]' ) { $id = substr($name,0,-2); return $this->renderOSList($value,$id,TRUE); } } //No Closing tag shipmentmethod.php000066600000020753151372127700010325 0ustar00setMainTable('shipmentmethods'); $this->_selectedOrdering = 'ordering'; } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * * @author RickG */ function getShipment() { if (empty($this->_data[$this->_id])) { $this->_data[$this->_id] = $this->getTable('shipmentmethods'); $this->_data[$this->_id]->load((int)$this->_id); if(empty($this->_data[$this->_id]->virtuemart_vendor_id)){ if(!class_exists('VirtueMartModelVendor')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php'); $this->_data[$this->_id]->virtuemart_vendor_id = VirtueMartModelVendor::getLoggedVendor();; } if($this->_data[$this->_id]->shipment_jplugin_id){ JPluginHelper::importPlugin('vmshipment'); $dispatcher = JDispatcher::getInstance(); $retValue = $dispatcher->trigger('plgVmDeclarePluginParamsShipment',array($this->_data[$this->_id]->shipment_element,$this->_data[$this->_id]->shipment_jplugin_id,&$this->_data[$this->_id])); } if($this->_data[$this->_id]->getCryptedFields()){ if(!class_exists('vmCrypt')){ require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmcrypt.php'); } if(isset($this->_data[$this->_id]->modified_on)){ $date = JFactory::getDate($this->_data[$this->_id]->modified_on); $date = $date->toUnix(); } else { $date = 0; } foreach($this->_data[$this->_id]->getCryptedFields() as $field){ if(isset($this->_data[$this->_id]->$field)){ $this->_data[$this->_id]->$field = vmCrypt::decrypt($this->_data[$this->_id]->$field,$date); } } } // vmdebug('$$this->_data getShipment',$this->_data); //if(!empty($this->_id)){ /* Add the shipmentcarreir shoppergroups */ $q = 'SELECT `virtuemart_shoppergroup_id` FROM #__virtuemart_shipmentmethod_shoppergroups WHERE `virtuemart_shipmentmethod_id` = "'.$this->_id.'"'; $this->_db->setQuery($q); $this->_data[$this->_id]->virtuemart_shoppergroup_ids = $this->_db->loadResultArray();# if(empty($this->_data[$this->_id]->virtuemart_shoppergroup_ids)) $this->_data[$this->_id]->virtuemart_shoppergroup_ids = 0; //} } return $this->_data[$this->_id]; } /** * Retireve a list of shipment from the database. * * @author RickG * @return object List of shipment objects */ public function getShipments() { if (JVM_VERSION===1) { $table = '#__plugins'; $enable = 'published'; $ext_id = 'id'; } else { $table = '#__extensions'; $enable = 'enabled'; $ext_id = 'extension_id'; } $query = ' `#__virtuemart_shipmentmethods`.* , `'.$table.'`.`name` as shipmentmethod_name FROM `#__virtuemart_shipmentmethods` '; $query .= 'JOIN `'.$table.'` ON `'.$table.'`.`'.$ext_id.'` = `#__virtuemart_shipmentmethods`.`shipment_jplugin_id` '; $whereString = ''; $select = ' * FROM `#__virtuemart_shipmentmethods_'.VMLANG.'` as l '; $joinedTables = ' JOIN `#__virtuemart_shipmentmethods` USING (`virtuemart_shipmentmethod_id`) '; $this->_data =$this->exeSortSearchListQuery(0,$select,$joinedTables,$whereString,' ',$this->_getOrdering() ); //$this->_data = $this->exeSortSearchListQuery(0,'',$query,$whereString,'',$this->_getOrdering('ordering')); if(isset($this->_data)){ if(!class_exists('shopfunctions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'shopfunctions.php'); foreach ($this->_data as $data){ /* Add the shipment shoppergroups */ $q = 'SELECT `virtuemart_shoppergroup_id` FROM #__virtuemart_shipmentmethod_shoppergroups WHERE `virtuemart_shipmentmethod_id` = "'.$data->virtuemart_shipmentmethod_id.'"'; $this->_db->setQuery($q); $data->virtuemart_shoppergroup_ids = $this->_db->loadResultArray(); /* Write the first 5 shoppergroups in the list */ $data->shipmentShoppersList = shopfunctions::renderGuiList('virtuemart_shoppergroup_id','#__virtuemart_shipmentmethod_shoppergroups','virtuemart_shipmentmethod_id',$data->virtuemart_shipmentmethod_id,'shopper_group_name','#__virtuemart_shoppergroups','virtuemart_shoppergroup_id','shoppergroup',4,0); } } return $this->_data; } /** * Bind the post data to the shipment tables and save it * * @author Max Milbers * @return boolean True is the save was successful, false otherwise. */ public function store(&$data) { if(is_object($data)){ $data = (array)$data; } if(!empty($data['params'])){ foreach($data['params'] as $k=>$v){ $data[$k] = $v; } } if(empty($data['virtuemart_vendor_id'])){ if(!class_exists('VirtueMartModelVendor')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php'); $data['virtuemart_vendor_id'] = VirtueMartModelVendor::getLoggedVendor(); } $table = $this->getTable('shipmentmethods'); if(isset($data['shipment_jplugin_id'])){ // missing string FIX, Bad way ? if (JVM_VERSION===1) { $tb = '#__plugins'; $ext_id = 'id'; } else { $tb = '#__extensions'; $ext_id = 'extension_id'; } $q = 'SELECT `element` FROM `' . $tb . '` WHERE `' . $ext_id . '` = "'.$data['shipment_jplugin_id'].'"'; $db = JFactory::getDbo(); $db->setQuery($q); $data['shipment_element'] = $db->loadResult(); $q = 'UPDATE `' . $tb . '` SET `enabled`= 1 WHERE `' . $ext_id . '` = "'.$data['shipment_jplugin_id'].'"'; $this->_db->setQuery($q); $this->_db->query(); JPluginHelper::importPlugin('vmshipment'); $dispatcher = JDispatcher::getInstance(); //bad trigger, we should just give it data, so that the plugins itself can check the data to be stored //so this trigger is now deprecated and will be deleted in vm3 $retValue = $dispatcher->trigger('plgVmSetOnTablePluginParamsShipment',array( $data['shipment_element'],$data['shipment_jplugin_id'],&$table)); $retValue = $dispatcher->trigger('plgVmSetOnTablePluginShipment',array( &$data,&$table)); } $table->bindChecknStore($data); $errors = $table->getErrors(); foreach($errors as $error){ vmError($error); } $xrefTable = $this->getTable('shipmentmethod_shoppergroups'); $xrefTable->bindChecknStore($data); $errors = $xrefTable->getErrors(); foreach($errors as $error){ vmError($error); } if (!class_exists('vmPSPlugin')) require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'); JPluginHelper::importPlugin('vmshipment'); //Add a hook here for other shipment methods, checking the data of the choosed plugin $dispatcher = JDispatcher::getInstance(); $retValues = $dispatcher->trigger('plgVmOnStoreInstallShipmentPluginTable', array( $data['shipment_jplugin_id'])); return $table->virtuemart_shipmentmethod_id; } /** * Creates a clone of a given shipmentmethod id * * @author Valérie Isaksen * @param int $virtuemart_shipmentmethod_id */ public function createClone ($id) { $this->setId ($id); $shipment = $this->getShipment (); $shipment->virtuemart_shipmentmethod_id = 0; $shipment->shipment_name = $shipment->shipment_name.' Copy'; if (!$clone = $this->store($shipment)) { vmError( 'createClone '. $shipment->getError() ); } return $clone; } } //no closing tag report.php000066600000034574151372127700006616 0ustar00setMainTable ('orders'); $this->setDatePresets (); $app = JFactory::getApplication (); $this->period = $app->getUserStateFromRequest ('com_virtuemart.revenue.period', 'period', 'last30', 'string'); //$post = JRequest::get ('post'); //vmdebug ('$post ', $post); if (empty($this->period) or $this->period != 'none') { $this->setPeriodByPreset (); } else { $this->setPeriod (); } $this->removevalidOrderingFieldName ('virtuemart_order_id'); $this->addvalidOrderingFieldName (array('product_quantity', 'o.virtuemart_order_id')); $this->_selectedOrdering = 'created_on'; } function correctTimeOffset(&$inputDate){ $config = JFactory::getConfig(); $this->siteOffset = $config->getValue('config.offset'); $date = new JDate($inputDate); $date->setTimezone($this->siteTimezone); $inputDate = $date->format('Y-m-d H:i:s',true); } /* * Set Start & end Date */ function setPeriod () { $this->from_period = JRequest::getVar ('from_period', $this->date_presets['last30']['from']); $this->until_period = JRequest::getVar ('until_period', $this->date_presets['last30']['until']); $config = JFactory::getConfig(); $siteOffset = $config->getValue('config.offset'); $this->siteTimezone = new DateTimeZone($siteOffset); $this->correctTimeOffset($this->from_period); $this->correctTimeOffset($this->until_period); } /* * Set Start & end Date if Var peroid */ function setPeriodByPreset () { $this->from_period = $this->date_presets[$this->period]['from']; $this->until_period = $this->date_presets[$this->period]['until']; $config = JFactory::getConfig(); $siteOffset = $config->getValue('config.offset'); $this->siteTimezone = new DateTimeZone($siteOffset); $this->correctTimeOffset($this->from_period); $this->correctTimeOffset($this->until_period); } function getItemsByRevenue ($revenue) { $q = 'select SUM(`product_quantity`) as product_quantity from `#__virtuemart_order_items` as i LEFT JOIN #__virtuemart_orders as o ON o.virtuemart_order_id=i.virtuemart_order_id ' . $this->whereItem . ' CAST(' . $this->intervals . ' AS DATE) = CAST("' . $revenue['intervals'] . '" AS DATE) '; $this->_db->setQuery ($q); //echo $this->_db->_sql; return $this->_db->loadResult (); } function getRevenueSortListOrderQuery ($sold = FALSE, $items = FALSE) { $selectFields = array(); $mainTable = ''; $joinTables = array(); $joinedTables = ''; $where = array(); // group always by intervals (day,week, ... or ID) and set grouping and defaut ordering $intervals = JRequest::getWord ('intervals', 'day'); switch ($intervals) { case 'day': $this->intervals = 'DATE( o.created_on )'; break; case 'week': $this->intervals = 'WEEK( o.created_on )'; break; case 'month': $this->intervals = 'MONTH( o.created_on )'; break; case 'year': $this->intervals = 'YEAR( o.created_on )'; break; default: // invidual grouping $this->intervals = 'o.created_on'; break; } // if(!empty($this->intervals)){ // $orderBy = $this->_getOrdering('o.`created_on`'); // } $selectFields['intervals'] = $this->intervals . ' AS intervals, CAST( o.`created_on` AS DATE ) AS created_on'; vmdebug('getRevenueSortListOrderQuery '.$intervals); if($intervals=='product_s'){ $selectFields[] = '`order_item_name`'; $selectFields[] = '`virtuemart_product_id`'; $groupBy = 'GROUP BY `virtuemart_product_id` '; } else { $groupBy = 'GROUP BY intervals '; } //$selectFields[] = 'COUNT(virtuemart_order_id) as number_of_orders'; //with tax => brutto //$selectFields[] = 'SUM(product_subtotal_with_tax) as order_total'; //without tax => netto //$selectFields[] = 'SUM(product_item_price) as order_subtotal'; $selectFields[] = 'SUM(product_discountedPriceWithoutTax * product_quantity) as order_subtotal_netto'; $selectFields[] = 'SUM(product_subtotal_with_tax) as order_subtotal_brutto'; $this->dates = ' DATE( o.created_on ) BETWEEN "' . $this->from_period . '" AND "' . $this->until_period . '" '; $statusList = array(); // Filter by statut if ($orderstates = JRequest::getVar ('order_status_code', array('C,S'))) { $query = 'SELECT `order_status_code` FROM `#__virtuemart_orderstates` WHERE published=1 '; $this->_db->setQuery ($query); $list = $this->_db->loadResultArray (); foreach ($orderstates as $val) { if (in_array ($val, $list)) { $statusList[] = '`i`.`order_status` = "' . $val . '"'; } } if ($statusList) { $where[] = '(' . implode (' OR ', $statusList) . ')'; } } //getRevenue // select wich table to order sum ordered $filterorders = JRequest::getvar ('filter_order', 'intervals'); $orderdir = (JRequest::getWord ('filter_order_Dir', NULL) == 'desc') ? 'desc' : ''; switch ($filterorders) { case 'o.virtuemart_order_id': $orderBy = ' ORDER BY count_order_id ' . $orderdir; $groupBy = 'GROUP BY intervals '; break; case 'product_quantity' : // GROUP BY product_quantity, intervals // ORDER BY `product_quantity` ASC // TODO grouping and ordering $orderBy = ' ORDER BY product_quantity ' . $orderdir; $groupBy = 'GROUP BY intervals '; //$selectFields['intervals'] = $this->intervals.' AS intervals, i.`created_on` '; break; case 'o.order_subtotal' : $orderBy = ' ORDER BY order_subtotal'; break; //getOrderItemsSumGrouped($this->intervals , $filterorders); break; default: // invidual grouping $orderBy = $this->_getOrdering (); vmdebug ('default case', $orderBy); //$this->intervals= '`o`.`created_on`'; // $orderBy = ' ORDER BY '.$filterorders.' '.$orderdir; break; } $selectFields[] = 'COUNT(DISTINCT o.virtuemart_order_id) as count_order_id'; $selectFields[] = 'SUM(product_quantity) as product_quantity'; $mainTable = '`#__virtuemart_order_items` as i'; $joinTables['orders'] = ' LEFT JOIN `#__virtuemart_orders` as o ON o.virtuemart_order_id=i.virtuemart_order_id '; if (count ($selectFields) > 0) { $select = implode (', ', $selectFields) . ' FROM ' . $mainTable; //$selectFindRows = 'SELECT COUNT(*) FROM '.$mainTable; if (count ($joinTables) > 0) { foreach ($joinTables as $table) { $joinedTables .= $table; } } } else { vmError ('No select fields given in getRevenueSortListOrderQuery', 'No select fields given'); return FALSE; } $virtuemart_product_id = JRequest::getInt ('virtuemart_product_id', FALSE); if ($virtuemart_product_id) { $where[] = 'i.virtuemart_product_id = "' . $virtuemart_product_id . '" '; } if (VmConfig::get ('multix', 'none') != 'none') { $vendorId = JRequest::getInt ('virtuemart_vendor_id', 0); if ($vendorId != 0) { $where[] = 'i.virtuemart_vendor_id = "' . $vendorId . '" '; } } if (count ($where) > 0) { $this->whereItem = ' WHERE ' . implode (' AND ', $where) . ' AND '; } else { $this->whereItem = ' WHERE '; } // $this->whereItem; /* WHERE differences with orders and items from orders are only date periods and ordering */ $whereString = $this->whereItem . $this->dates; return $this->exeSortSearchListQuery (1, $select, $joinedTables, $whereString, $groupBy, $orderBy); } /** * Retrieve a list of report items from the database. * * @author Wicksj * @param string $noLimit True if no record count limit is used, false otherwise * @return object List of order objects */ function getRevenue ($noLimit = FALSE) { return $this->getRevenueSortListOrderQuery (); } /** * Retrieve a list of report items from the database. * DONT know why this ???? Patrick Kohl * * @author Wicksj * @param string $noLimit True if no record count limit is used, false otherwise * @return object List of order objects */ function getOrderItems ($noLimit = FALSE) { // $db = JFactory::getDBO(); $query = "SELECT `product_name`, `product_sku`, "; $query .= "i.created_on as order_date, "; $query .= "SUM(product_quantity) as product_quantity "; $query .= "FROM #__virtuemart_order_items i, #__virtuemart_orders o, #__virtuemart_products p "; $query .= "WHERE i.created_on BETWEEN '{$this->start_date} 00:00:00' AND '{$this->until_period} 23:59:59' "; $query .= "AND o.virtuemart_order_id=i.virtuemart_order_id "; $query .= "AND i.virtuemart_product_id=p.virtuemart_product_id "; $query .= "GROUP BY product_sku, product_name, order_date "; $query .= " ORDER BY order_date, product_name ASC"; if ($noLimit) { $this->_data = $this->_getList ($query); } else { $this->_data = $this->_getList ($query, $this->getState ('limitstart'), $this->getState ('limit')); } if (!$this->_total) { $this->_total = $this->_getListCount ($query); } return $this->_data; } public function setDatePresets () { if ($this->date_presets) { return $this->date_presets; } // set date presets $curDate = JFactory::getDate (); $curDate = $curDate->toUnix (); $curDate = mktime (0, 0, 0, date ('m', $curDate), date ('d', $curDate), date ('Y', $curDate)); $monday = (date ('w', $curDate) == 1) ? $curDate : strtotime ('last Monday', $curDate); $this->date_presets['last90'] = array( 'name' => JText::_ ('COM_VIRTUEMART_REPORT_PERIOD_LAST90'), 'from' => date ('Y-m-d', strtotime ('-89 day', $curDate)), 'until' => date ('Y-m-d', $curDate)); $this->date_presets['last60'] = array( 'name' => JText::_ ('COM_VIRTUEMART_REPORT_PERIOD_LAST60'), 'from' => date ('Y-m-d', strtotime ('-59 day', $curDate)), 'until' => date ('Y-m-d', $curDate)); $this->date_presets['last30'] = array( 'name' => JText::_ ('COM_VIRTUEMART_REPORT_PERIOD_LAST30'), 'from' => date ('Y-m-d', strtotime ('-29 day', $curDate)), 'until' => date ('Y-m-d', $curDate)); $this->date_presets['today'] = array( 'name' => JText::_ ('COM_VIRTUEMART_REPORT_PERIOD_TODAY'), 'from' => date ('Y-m-d', $curDate), 'until' => date ('Y-m-d', $curDate)); $this->date_presets['this-week'] = array( 'name' => JText::_ ('COM_VIRTUEMART_REPORT_PERIOD_THIS_WEEK'), 'from' => date ('Y-m-d', $monday), 'until' => date ('Y-m-d', strtotime ('+6 day', $monday))); $this->date_presets['this-month'] = array( 'name' => JText::_ ('COM_VIRTUEMART_REPORT_PERIOD_THIS_MONTH'), 'from' => date ('Y-m-d', mktime (0, 0, 0, date ('n', $curDate), 1, date ('Y', $curDate))), 'until' => date ('Y-m-d', mktime (0, 0, 0, date ('n', $curDate) + 1, 0, date ('Y', $curDate)))); $this->date_presets['this-year'] = array( 'name' => JText::_ ('COM_VIRTUEMART_REPORT_PERIOD_THIS_YEAR'), 'from' => date ('Y-m-d', mktime (0, 0, 0, 1, 1, date ('Y', $curDate))), 'until' => date ('Y-m-d', mktime (0, 0, 0, 12, 31, date ('Y', $curDate)))); } public function renderDateSelectList () { // simpledate select $select = ''; $options = array(JHTML::_ ('select.option', 'none', '- ' . JText::_ ('COM_VIRTUEMART_REPORT_SET_PERIOD') . ' -', 'text', 'value')); $app = JFactory::getApplication (); $select = $app->getUserStateFromRequest ('com_virtuemart.revenue.period', 'period', 'last30', 'string'); foreach ($this->date_presets as $name => $value) { $options[] = JHTML::_ ('select.option', $name, JText::_ ($value['name']), 'text', 'value'); } $listHTML = JHTML::_ ('select.genericlist', $options, 'period', 'size="7" class="inputbox" onchange="this.form.submit();" ', 'text', 'value', $select); //$listHTML = JHTML::_ ('select.genericlist', $options, 'period', 'size="7" class="inputbox" ', 'text', 'value', $select); return $listHTML; } public function renderIntervalsList () { $intervals = JRequest::getWord ('intervals', 'day'); $options = array(); $options[] = JHTML::_ ('select.option', JText::_ ('COM_VIRTUEMART_PRODUCT_S'), 'product_s'); $options[] = JHTML::_ ('select.option', JText::_ ('COM_VIRTUEMART_ORDERS'), 'orders'); $options[] = JHTML::_ ('select.option', JText::_ ('COM_VIRTUEMART_REPORT_INTERVAL_GROUP_DAILY'), 'day'); $options[] = JHTML::_ ('select.option', JText::_ ('COM_VIRTUEMART_REPORT_INTERVAL_GROUP_WEEKLY'), 'week'); $options[] = JHTML::_ ('select.option', JText::_ ('COM_VIRTUEMART_REPORT_INTERVAL_GROUP_MONTHLY'), 'month'); $options[] = JHTML::_ ('select.option', JText::_ ('COM_VIRTUEMART_REPORT_INTERVAL_GROUP_YEARLY'), 'year'); //$listHTML = JHTML::_ ('select.genericlist', $options, 'intervals', 'class="inputbox" onchange="this.form.submit();" size="5"', 'text', 'value', $intervals); $listHTML = JHTML::_ ('select.genericlist', $options, 'intervals', 'class="inputbox" size="6"', 'text', 'value', $intervals); return $listHTML; } public function updateOrderItems () { $q = 'UPDATE #__virtuemart_order_items SET `product_discountedPriceWithoutTax`=( (IF(product_final_price is NULL, 0.00,product_final_price) - IF(product_tax is NULL, 0.00,product_tax) )) WHERE `product_discountedPriceWithoutTax` IS NULL'; $this->_db = JFactory::getDBO(); $this->_db->setQuery($q); $this->_db->query(); } } paymentmethod.php000066600000023010151372127700010140 0ustar00setMainTable('paymentmethods'); $this->_selectedOrdering = 'ordering'; } /** * Gets the virtuemart_paymentmethod_id with a plugin and vendorId * * @author Max Milbers */ public function getIdbyCodeAndVendorId($jpluginId,$vendorId=1){ if(!$jpluginId) return 0; $q = 'SELECT `virtuemart_paymentmethod_id` FROM #__virtuemart_paymentmethods WHERE `payment_jplugin_id` = "'.$jpluginId.'" AND `virtuemart_vendor_id` = "'.$vendorId.'" '; $this->_db->setQuery($q); return $this->_db->loadResult(); } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * * @author Max Milbers */ public function getPayment(){ if (empty($this->_data[$this->_id])) { $this->_data[$this->_id] = $this->getTable('paymentmethods'); $this->_data[$this->_id]->load((int)$this->_id); if(empty($this->_data->virtuemart_vendor_id)){ if(!class_exists('VirtueMartModelVendor')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php'); $this->_data[$this->_id]->virtuemart_vendor_id = VirtueMartModelVendor::getLoggedVendor(); } if($this->_data[$this->_id]->payment_jplugin_id){ JPluginHelper::importPlugin('vmpayment'); $dispatcher = JDispatcher::getInstance(); $retValue = $dispatcher->trigger('plgVmDeclarePluginParamsPayment',array($this->_data[$this->_id]->payment_element,$this->_data[$this->_id]->payment_jplugin_id,&$this->_data[$this->_id])); } if($this->_data[$this->_id]->getCryptedFields()){ if(!class_exists('vmCrypt')){ require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmcrypt.php'); } if(isset($this->_data[$this->_id]->modified_on)){ $date = JFactory::getDate($this->_data[$this->_id]->modified_on); $date = $date->toUnix(); } else { $date = 0; } foreach($this->_data[$this->_id]->getCryptedFields() as $field){ if(isset($this->_data[$this->_id]->$field)){ $this->_data[$this->_id]->$field = vmCrypt::decrypt($this->_data[$this->_id]->$field,$date); } } } $q = 'SELECT `virtuemart_shoppergroup_id` FROM #__virtuemart_paymentmethod_shoppergroups WHERE `virtuemart_paymentmethod_id` = "'.$this->_id.'"'; $this->_db->setQuery($q); $this->_data[$this->_id]->virtuemart_shoppergroup_ids = $this->_db->loadResultArray(); if(empty($this->_data[$this->_id]->virtuemart_shoppergroup_ids)) $this->_data[$this->_id]->virtuemart_shoppergroup_ids = 0; } return $this->_data[$this->_id]; } /** * Retireve a list of calculation rules from the database. * * @author Max Milbers * @param string $onlyPuiblished True to only retreive the publish Calculation rules, false otherwise * @param string $noLimit True if no record count limit is used, false otherwise * @return object List of calculation rule objects */ public function getPayments($onlyPublished=false, $noLimit=false) { $where = array(); if ($onlyPublished) { $where[] = ' `#__virtuemart_paymentmethods`.`published` = 1'; } $whereString = ''; if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where) ; $select = ' * FROM `#__virtuemart_paymentmethods_'.VMLANG.'` as l '; $joinedTables = ' JOIN `#__virtuemart_paymentmethods` USING (`virtuemart_paymentmethod_id`) '; $this->_data =$this->exeSortSearchListQuery(0,$select,$joinedTables,$whereString,' ',$this->_getOrdering() ); //$this->exeSortSearchListQuery(0,'*',' FROM `#__virtuemart_paymentmethods`',$whereString,'',$this->_getOrdering('ordering')); if(isset($this->_data)){ if(!class_exists('shopfunctions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'shopfunctions.php'); foreach ($this->_data as $data){ /* Add the paymentmethod shoppergroups */ $q = 'SELECT `virtuemart_shoppergroup_id` FROM #__virtuemart_paymentmethod_shoppergroups WHERE `virtuemart_paymentmethod_id` = "'.$data->virtuemart_paymentmethod_id.'"'; $this->_db->setQuery($q); $data->virtuemart_shoppergroup_ids = $this->_db->loadResultArray(); /* Write the first 5 shoppergroups in the list */ $data->paymShoppersList = shopfunctions::renderGuiList('virtuemart_shoppergroup_id','#__virtuemart_paymentmethod_shoppergroups','virtuemart_paymentmethod_id',$data->virtuemart_paymentmethod_id,'shopper_group_name','#__virtuemart_shoppergroups','virtuemart_shoppergroup_id','shoppergroup',4,0); } } return $this->_data; } /** * Bind the post data to the paymentmethod tables and save it * * @author Max Milbers * @return boolean True is the save was successful, false otherwise. */ public function store(&$data) { if(is_object($data)){ $data = (array)$data; } if(!empty($data['params'])){ foreach($data['params'] as $k=>$v){ $data[$k] = $v; } } if(empty($data['virtuemart_vendor_id'])){ if(!class_exists('VirtueMartModelVendor')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php'); $data['virtuemart_vendor_id'] = VirtueMartModelVendor::getLoggedVendor(); } $table = $this->getTable('paymentmethods'); if(isset($data['payment_jplugin_id'])){ // missing string FIX, Bad way ? if (JVM_VERSION===1) { $tb = '#__plugins'; $ext_id = 'id'; } else { $tb = '#__extensions'; $ext_id = 'extension_id'; } $q = 'SELECT `element` FROM `' . $tb . '` WHERE `' . $ext_id . '` = "'.$data['payment_jplugin_id'].'"'; $this->_db->setQuery($q); $data['payment_element'] = $this->_db->loadResult(); $q = 'UPDATE `' . $tb . '` SET `enabled`= 1 WHERE `' . $ext_id . '` = "'.$data['payment_jplugin_id'].'"'; $this->_db->setQuery($q); $this->_db->query(); // special case moneybookers if ( strpos($data['payment_element'] , "moneybookers" ) !==false) { $q = 'UPDATE `#__extensions` SET `enabled`= 1 WHERE `element` ="moneybookers"'; $this->_db->setQuery($q); $this->_db->query(); } JPluginHelper::importPlugin('vmpayment'); $dispatcher = JDispatcher::getInstance(); $retValue = $dispatcher->trigger('plgVmSetOnTablePluginParamsPayment',array( $data['payment_element'],$data['payment_jplugin_id'],&$table)); } $table->bindChecknStore($data); $errors = $table->getErrors(); foreach($errors as $error){ vmError($error); } $xrefTable = $this->getTable('paymentmethod_shoppergroups'); $xrefTable->bindChecknStore($data); $errors = $xrefTable->getErrors(); foreach($errors as $error){ vmError($error); } if (!class_exists('vmPSPlugin')) require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'); JPluginHelper::importPlugin('vmpayment'); //Add a hook here for other shipment methods, checking the data of the choosed plugin $dispatcher = JDispatcher::getInstance(); $retValues = $dispatcher->trigger('plgVmOnStoreInstallPaymentPluginTable', array( $data['payment_jplugin_id'])); return $table->virtuemart_paymentmethod_id; } /** * Publish a field * * @author Max Milbers * */ /* public function published( $row, $i, $variable = 'published' ) { $imgY = 'tick.png'; $imgX = 'publish_x.png'; $img = $row->$variable ? $imgY : $imgX; $task = $row->$variable ? 'unpublish' : 'publish'; $alt = $row->$variable ? JText::_('COM_VIRTUEMART_PUBLISHED') : JText::_('COM_VIRTUEMART_UNPUBLISHED'); $action = $row->$variable ? JText::_('COM_VIRTUEMART_UNPUBLISH_ITEM') : JText::_('COM_VIRTUEMART_PUBLISH_ITEM'); $href = ' '. $alt .'' ; return $href; }*/ /** * Due the new plugin system this should be obsolete * function to render the payment plugin list * * @author Max Milbers * * @param radio list of creditcards * @return html */ public function renderPaymentList($selectedPaym=0,$selecedCC=0){ $payms = self::getPayments(false,true); $listHTML=''; foreach($payms as $item){ $checked=''; if($item->virtuemart_paymentmethod_id==$selectedPaym){ $checked='"checked"'; } $listHTML .= ''.$item->payment_name.'
'; $listHTML .= '
'; } return $listHTML; } /** * Creates a clone of a given shipmentmethod id * * @author Valérie Isaksen * @param int $virtuemart_shipmentmethod_id */ public function createClone ($id) { $this->setId ($id); $payment = $this->getPayment (); $payment->virtuemart_paymentmethod_id = 0; $payment->payment_name = $payment->payment_name.' Copy'; if (!$clone = $this->store($payment)) { vmError( 'createClone '. $payment->getError() ); } return $clone; } } country.php000066600000006455151372127700007003 0ustar00setMainTable('countries'); array_unshift($this->_validOrderingFieldName,'country_name'); $this->_selectedOrdering = 'country_name'; $this->_selectedOrderingDir = 'ASC'; } /** * Retreive a country record given a country code. * * @author RickG * @param string $code Country code to lookup * @return object Country object from database */ function getCountryByCode($code) { $db = JFactory::getDBO(); $countryCodeLength = strlen($code); switch ($countryCodeLength) { case 2: $countryCodeFieldname = 'country_2_code'; break; case 3: $countryCodeFieldname = 'country_3_code'; break; default: return false; } $query = 'SELECT *'; $query .= ' FROM `#__virtuemart_countries`'; $query .= ' WHERE `' . $countryCodeFieldname . '` = "' . $code . '"'; $db->setQuery($query); return $db->loadObject(); } /** * Retrieve a list of countries from the database. * * @author RickG * @author Max Milbers * @param string $onlyPublished True to only retrieve the publish countries, false otherwise * @param string $noLimit True if no record count limit is used, false otherwise * @return object List of country objects */ function getCountries($onlyPublished=true, $noLimit=false, $filterCountry = false) { $where = array(); $this->_noLimit = $noLimit; // $query = 'SELECT * FROM `#__virtuemart_countries` '; /* add filters */ if ($onlyPublished) $where[] = '`published` = 1'; if($filterCountry){ $filterCountry = '"%' . $this->_db->getEscaped( $filterCountry, true ) . '%"' ; //$keyword = $this->_db->Quote($filterCountry, false); $where[] = '`country_name` LIKE '.$filterCountry.' OR `country_2_code` LIKE '.$filterCountry.' OR `country_3_code` LIKE '.$filterCountry; } $whereString = ''; if (count($where) > 0) $whereString = ' WHERE '.implode(' AND ', $where) ; $ordering = $this->_getOrdering(); return $this->_data = $this->exeSortSearchListQuery(0,'*',' FROM `#__virtuemart_countries`',$whereString,'',$ordering); } } //no closing tag pure phporders.php000066600000222377151372127700006601 0ustar00db is never used in the model ? * @package VirtueMart * @author RolandD */ class VirtueMartModelOrders extends VmModel { /** * constructs a VmModel * setMainTable defines the maintable of the model * @author Max Milbers */ function __construct() { parent::__construct(); $this->setMainTable('orders'); $this->addvalidOrderingFieldName(array('order_name','order_email','payment_method','virtuemart_order_id' ) ); } /** * This function gets the orderId, for anonymous users * @author Max Milbers */ public function getOrderIdByOrderPass($orderNumber,$orderPass){ $db = JFactory::getDBO(); $q = 'SELECT `virtuemart_order_id` FROM `#__virtuemart_orders` WHERE `order_pass`="'.$db->getEscaped($orderPass).'" AND `order_number`="'.$db->getEscaped($orderNumber).'"'; $db->setQuery($q); $orderId = $db->loadResult(); // vmdebug('getOrderIdByOrderPass '.$orderId); return $orderId; } /** * This function gets the orderId, for payment response * author Valerie Isaksen */ public static function getOrderIdByOrderNumber($orderNumber){ $db = JFactory::getDBO(); $q = 'SELECT `virtuemart_order_id` FROM `#__virtuemart_orders` WHERE `order_number`="'.$db->getEscaped($orderNumber).'"'; $db->setQuery($q); $orderId = $db->loadResult(); return $orderId; } /** * This function seems completly broken, JRequests are not allowed in the model, sql not escaped * This function gets the secured order Number, to send with paiement * */ public function getOrderNumber($virtuemart_order_id){ $db = JFactory::getDBO(); $q = 'SELECT `order_number` FROM `#__virtuemart_orders` WHERE virtuemart_order_id="'.(int)$virtuemart_order_id.'" '; $db->setQuery($q); $OrderNumber = $db->loadResult(); return $OrderNumber; } /** * Was also broken, actually used? * * get next/previous order id * */ public function getOrderId($order_id, $direction ='DESC') { if ($direction == 'ASC') { $arrow ='>'; } else { $arrow ='<'; } $db = JFactory::getDBO(); $q = 'SELECT `virtuemart_order_id` FROM `#__virtuemart_orders` WHERE `virtuemart_order_id`'.$arrow.(int)$order_id; $q.= ' ORDER BY `virtuemart_order_id` '.$direction ; $db->setQuery($q); if ($oderId = $db->loadResult()) { return $oderId ; } return 0 ; } /** * This is a proxy function to return an order safely, we may set the getOrder function to private * Maybe the right place would be the controller, cause there are JRequests in it. But for a fast solution, * still better than to have it 3-4 times in the view.html.php of the views. * @author Max Milbers * * @return array */ public function getMyOrderDetails($orderID = 0, $orderNumber = false, $orderPass = false){ $_currentUser = JFactory::getUser(); $cuid = $_currentUser->get('id'); $orderDetails = false; // If the user is not logged in, we will check the order number and order pass if(empty($orderID) and empty($cuid)){ // If the user is not logged in, we will check the order number and order pass if ($orderPass = JRequest::getString('order_pass',$orderPass)){ $orderNumber = JRequest::getString('order_number',$orderNumber); $orderId = $this->getOrderIdByOrderPass($orderNumber,$orderPass); if(empty($orderId)){ echo JText::_('COM_VIRTUEMART_RESTRICTED_ACCESS'); return false; } $orderDetails = $this->getOrder($orderId); } } else { // If the user is logged in, we will check if the order belongs to him $virtuemart_order_id = JRequest::getInt('virtuemart_order_id',$orderID) ; if (!$virtuemart_order_id) { $virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber(JRequest::getString('order_number')); } $orderDetails = $this->getOrder($virtuemart_order_id); if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check("admin")) { if(!isset($orderDetails['details']['BT']->virtuemart_user_id)){ $orderDetails['details']['BT']->virtuemart_user_id = 0; } //if(!empty($orderDetails['details']['BT']->virtuemart_user_id)){ vmdebug('getMyOrderDetails',$cuid,$orderDetails['details']['BT']->virtuemart_user_id); if ($orderDetails['details']['BT']->virtuemart_user_id != $cuid) { echo JText::_('COM_VIRTUEMART_RESTRICTED_ACCESS'); return false; } //} } } return $orderDetails; } /** * Load a single order, Attention, this function is not protected! Do the right manangment before, to be certain * we suggest to use getMyOrderDetails */ public function getOrder($virtuemart_order_id){ //sanitize id $virtuemart_order_id = (int)$virtuemart_order_id; $db = JFactory::getDBO(); $order = array(); // Get the order details $q = "SELECT u.*,o.*, s.order_status_name FROM #__virtuemart_orders o LEFT JOIN #__virtuemart_orderstates s ON s.order_status_code = o.order_status LEFT JOIN #__virtuemart_order_userinfos u ON u.virtuemart_order_id = o.virtuemart_order_id WHERE o.virtuemart_order_id=".$virtuemart_order_id; $db->setQuery($q); $order['details'] = $db->loadObjectList('address_type'); // Get the order history $q = "SELECT * FROM #__virtuemart_order_histories WHERE virtuemart_order_id=".$virtuemart_order_id." ORDER BY virtuemart_order_history_id ASC"; $db->setQuery($q); $order['history'] = $db->loadObjectList(); // Get the order items $q = 'SELECT virtuemart_order_item_id, product_quantity, order_item_name, order_item_sku, i.virtuemart_product_id, product_item_price, product_final_price, product_basePriceWithTax, product_discountedPriceWithoutTax, product_priceWithoutTax, product_subtotal_with_tax, product_subtotal_discount, product_tax, product_attribute, order_status, p.product_available_date, p.product_availability, intnotes, virtuemart_category_id FROM (#__virtuemart_order_items i LEFT JOIN #__virtuemart_products p ON p.virtuemart_product_id = i.virtuemart_product_id) LEFT JOIN #__virtuemart_product_categories c ON p.virtuemart_product_id = c.virtuemart_product_id WHERE `virtuemart_order_id`="'.$virtuemart_order_id.'" group by `virtuemart_order_item_id`'; //group by `virtuemart_order_id`'; Why ever we added this, it makes trouble, only one order item is shown then. // without group by we get the product 3 times, when it is in 3 categories and similar, so we need a group by //lets try group by `virtuemart_order_item_id` $db->setQuery($q); $order['items'] = $db->loadObjectList(); // Get the order items $q = "SELECT * FROM #__virtuemart_order_calc_rules AS z WHERE virtuemart_order_id=".$virtuemart_order_id; $db->setQuery($q); $order['calc_rules'] = $db->loadObjectList(); // vmdebug('getOrder my order',$order); return $order; } /** * Select the products to list on the product list page * @param $uid integer Optional user ID to get the orders of a single user * @param $_ignorePagination boolean If true, ignore the Joomla pagination (for embedded use, default false) */ public function getOrdersList($uid = 0, $noLimit = false) { // vmdebug('getOrdersList'); $this->_noLimit = $noLimit; $select = " o.*, CONCAT_WS(' ',u.first_name,u.middle_name,u.last_name) AS order_name " .',u.email as order_email,pm.payment_name AS payment_method '; $from = $this->getOrdersListQuery(); /* $_filter = array(); if ($uid > 0) { $_filter[] = ('u.virtuemart_user_id = ' . (int)$uid); }*/ $where = array(); if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check('storeadmin')){ $myuser =JFactory::getUser(); $where[]= ' u.virtuemart_user_id = ' . (int)$myuser->id.' AND o.virtuemart_vendor_id = "1" '; } else { if(empty($uid)){ $where[]= ' o.virtuemart_vendor_id = "1" '; } else { $where[]= ' u.virtuemart_user_id = ' . (int)$uid.' AND o.virtuemart_vendor_id = "1" '; } } if ($search = JRequest::getString('search', false)){ $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; $search = str_replace(' ','%',$search); $searchFields = array(); $searchFields[] = 'u.first_name'; $searchFields[] = 'u.middle_name'; $searchFields[] = 'u.last_name'; $searchFields[] = 'o.order_number'; $searchFields[] = 'u.company'; $searchFields[] = 'u.email'; $searchFields[] = 'u.phone_1'; $searchFields[] = 'u.address_1'; $searchFields[] = 'u.zip'; $where[] = implode (' LIKE '.$search.' OR ', $searchFields) . ' LIKE '.$search.' '; //$where[] = ' ( u.first_name LIKE '.$search.' OR u.middle_name LIKE '.$search.' OR u.last_name LIKE '.$search.' OR `order_number` LIKE '.$search.')'; } $order_status_code = JRequest::getString('order_status_code', false); if ($order_status_code and $order_status_code!=-1){ $where[] = ' o.order_status = "'.$order_status_code.'" '; } if (count ($where) > 0) { $whereString = ' WHERE (' . implode (' AND ', $where) . ') '; } else { $whereString = ''; } if ( JRequest::getCmd('view') == 'orders') { $ordering = $this->_getOrdering(); } else { $ordering = ' order by o.modified_on DESC'; } $this->_data = $this->exeSortSearchListQuery(0,$select,$from,$whereString,'',$ordering); return $this->_data ; } /** * List of tables to include for the product query * @author RolandD */ private function getOrdersListQuery() { return ' FROM #__virtuemart_orders as o LEFT JOIN #__virtuemart_order_userinfos as u ON u.virtuemart_order_id = o.virtuemart_order_id AND u.address_type="BT" LEFT JOIN #__virtuemart_paymentmethods_'.VMLANG.' as pm ON o.virtuemart_paymentmethod_id = pm.virtuemart_paymentmethod_id '; } /** * Update an order item status * @author Max Milbers * @author Ondřej Spilka - used for item edit also * @author Maik Künnemann */ public function updateSingleItem($virtuemart_order_item_id, &$orderdata, $orderUpdate = false) { //vmdebug('updateSingleItem',$virtuemart_order_item_id,$orderdata); $table = $this->getTable('order_items'); $table->load($virtuemart_order_item_id); $oldOrderStatus = $table->order_status; if(empty($oldOrderStatus)){ $oldOrderStatus = $orderdata->current_order_status; if($orderUpdate and empty($oldOrderStatus)){ $oldOrderStatus = 'P'; } } // $table->order_status = $orderdata->orderstatus; JPluginHelper::importPlugin('vmcustom'); $_dispatcher = JDispatcher::getInstance(); $_returnValues = $_dispatcher->trigger('plgVmOnUpdateSingleItem',array($table,&$orderdata)); $dataT = get_object_vars($table); // $doUpdate = JRequest::getString('update_values'); $orderdatacopy = $orderdata; $data = array_merge($dataT,(array)$orderdatacopy); // $data['order_status'] = $orderdata->orderstatus; if (!class_exists('CurrencyDisplay')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'); } $this->_currencyDisplay = CurrencyDisplay::getInstance(); $rounding = $this->_currencyDisplay->_priceConfig['salesPrice'][1]; if ( $orderUpdate and !empty($data['virtuemart_order_item_id'])) { //get tax calc_value of product VatTax $db = JFactory::getDBO(); $sql = "SELECT `calc_value` FROM `#__virtuemart_order_calc_rules` WHERE `virtuemart_order_id` = ".$data['virtuemart_order_id']." AND `virtuemart_order_item_id` = ".$data['virtuemart_order_item_id']." AND `calc_kind` = 'VatTax' "; $db->setQuery($sql); $taxCalcValue = $db->loadResult(); if($data['calculate_product_tax']) { if(!$taxCalcValue){ //Could be a new item, missing the tax rules, we try to get one of another product. //get tax calc_value of product VatTax $db = JFactory::getDBO(); $sql = "SELECT `calc_value` FROM `#__virtuemart_order_calc_rules` WHERE `virtuemart_order_id` = ".$data['virtuemart_order_id']." AND `calc_kind` = 'VatTax' "; $db->setQuery($sql); $taxCalcValue = $db->loadResult(); } if(empty($data['product_subtotal_discount']))$data['product_subtotal_discount'] = 0.0; // "",null,0,NULL, FALSE => 0.0 //We do two cases, either we have the final amount and discount if(!empty($data['product_final_price']) and $data['product_final_price']!=0){ if(empty($data['product_tax']) or $data['product_tax']==0){ $data['product_tax'] = $data['product_final_price'] * $taxCalcValue / ($taxCalcValue + 100); //vmdebug($data['product_final_price'] .' * '.$taxCalcValue.' / '.($taxCalcValue + 100).' = '.$data['product_tax']); } if(empty($data['product_item_price']) or $data['product_item_price']==0){ if(empty($data['product_tax']))$data['product_tax'] = 0.0; $data['product_item_price'] = round($data['product_final_price'], $rounding) - $data['product_tax']; $data['product_discountedPriceWithoutTax'] = 0.0;// round($data['product_final_price'], $rounding) ; $data['product_priceWithoutTax'] = 0.0; $data['product_basePriceWithTax'] = round($data['product_final_price'], $rounding) - $data['product_subtotal_discount']; } } else //or we have the base price and a manually set discount. if(!empty($data['product_item_price']) and $data['product_item_price']!=0){ if(empty($data['product_tax']) or $data['product_tax']==0){ $data['product_tax'] = ($data['product_item_price']-$data['product_subtotal_discount']) * ($taxCalcValue/100.0); } $data['product_discountedPriceWithoutTax'] = 0.0; $data['product_priceWithoutTax'] = 0.0; $data['product_final_price'] = round($data['product_item_price'], $rounding) + $data['product_tax'] + $data['product_subtotal_discount']; $data['product_basePriceWithTax'] = round($data['product_final_price'], $rounding) - $data['product_subtotal_discount']; } } //$data['product_subtotal_discount'] = (round($orderdata->product_final_price, $rounding) - round($data['product_basePriceWithTax'], $rounding)) * $orderdata->product_quantity; $data['product_subtotal_with_tax'] = round($data['product_final_price'], $rounding) * $orderdata->product_quantity; } $table->bindChecknStore($data); if ( $orderUpdate ) { if ( empty($data['order_item_sku']) ) { //update product identification $db = JFactory::getDBO(); $prolang = '#__virtuemart_products_' . VMLANG; $oi = " #__virtuemart_order_items"; $protbl = "#__virtuemart_products"; $sql = "UPDATE $oi, $protbl, $prolang" . " SET $oi.order_item_sku=$protbl.product_sku, $oi.order_item_name=$prolang.product_name ". " WHERE $oi.virtuemart_product_id=$protbl.virtuemart_product_id " . " and $oi.virtuemart_product_id=$prolang.virtuemart_product_id " . " and $oi.virtuemart_order_item_id=$virtuemart_order_item_id"; $db->setQuery($sql); if ($db->query() === false) { vmError($db->getError()); } } } // Update the order item history //$this->_updateOrderItemHist($id, $order_status, $customer_notified, $comment); $errors = $table->getErrors(); foreach($errors as $error){ vmError( get_class( $this ).'::store '.$error); } //OSP update cartRules/shipment/payment //it would seem strange this is via item edit //but in general, shipment and payment would be tractated as another items of the order //in datas they are not, bu okay we have it here and functional //moreover we can compute all aggregate values here via one aggregate SQL if ( $orderUpdate ) { $db = JFactory::getDBO(); $ordid = $table->virtuemart_order_id; //cartRules $calc_rules = JRequest::getVar('calc_rules','', '', 'array'); $calc_rules_amount = 0; $calc_rules_discount_amount = 0; $calc_rules_tax_amount = 0; if(!empty($calc_rules)) { foreach($calc_rules as $calc_kind => $calc_rule) { foreach($calc_rule as $virtuemart_order_calc_rule_id => $calc_amount) { $sql = "UPDATE `#__virtuemart_order_calc_rules` SET `calc_amount`=$calc_amount WHERE `virtuemart_order_calc_rule_id`=$virtuemart_order_calc_rule_id"; $db->setQuery($sql); if(isset($calc_amount)) $calc_rules_amount += $calc_amount; if ($calc_kind == 'DBTaxRulesBill' || $calc_kind == 'DATaxRulesBill') { $calc_rules_discount_amount += $calc_amount; } if ($calc_kind == 'taxRulesBill') { $calc_rules_tax_amount += $calc_amount; } if ($db->query() === false) { vmError($db->getError()); } } } } //shipment $os = JRequest::getString('order_shipment'); $ost = JRequest::getString('order_shipment_tax'); if ( $os!="" ) { $sql = "UPDATE `#__virtuemart_orders` SET `order_shipment`=$os,`order_shipment_tax`=$ost WHERE `virtuemart_order_id`=$ordid"; $db->setQuery($sql); if ($db->query() === false) { vmError($db->getError()); } } //payment $op = JRequest::getString('order_payment'); $opt = JRequest::getString('order_payment_tax'); if ( $op!="" ) { $sql = "UPDATE `#__virtuemart_orders` SET `order_payment`=$op,`order_payment_tax`=$opt WHERE `virtuemart_order_id`=$ordid"; $db->setQuery($sql); if ($db->query() === false) { vmError($db->getError()); } } $sql = " UPDATE `#__virtuemart_orders` SET `order_total`=(SELECT sum(product_final_price*product_quantity) FROM #__virtuemart_order_items where `virtuemart_order_id`=$ordid)+`order_shipment`+`order_shipment_tax`+`order_payment`+`order_payment_tax`+$calc_rules_amount, `order_discountAmount`=(SELECT sum(product_subtotal_discount) FROM #__virtuemart_order_items where `virtuemart_order_id`=$ordid), `order_billDiscountAmount`=`order_discountAmount`+$calc_rules_discount_amount, `order_salesPrice`=(SELECT sum(product_final_price*product_quantity) FROM #__virtuemart_order_items where `virtuemart_order_id`=$ordid), `order_tax`=(SELECT sum( product_tax*product_quantity) FROM #__virtuemart_order_items where `virtuemart_order_id`=$ordid), `order_subtotal`=(SELECT sum(ROUND(product_item_price, ". $rounding .")*product_quantity) FROM #__virtuemart_order_items where `virtuemart_order_id`=$ordid),"; if(JRequest::getString('calculate_billTaxAmount')) { $sql .= "`order_billTaxAmount`=(SELECT sum( product_tax*product_quantity) FROM #__virtuemart_order_items where `virtuemart_order_id`=$ordid)+`order_shipment_tax`+`order_payment_tax`+$calc_rules_tax_amount"; } else { $sql .= "`order_billTaxAmount`=".JRequest::getString('order_billTaxAmount'); } $sql .= " WHERE `virtuemart_order_id`=$ordid"; $db->setQuery($sql); if ($db->query() === false) { vmError('updateSingleItem '.$db->getError().' and '.$sql); } } $this->handleStockAfterStatusChangedPerProduct($orderdata->order_status, $oldOrderStatus, $table,$table->product_quantity); // } } /** * Strange name is just temporarly * * @param unknown_type $order_id * @param unknown_type $order_status * @author Max Milbers */ var $useDefaultEmailOrderStatus = true; public function updateOrderStatus($orders=0, $order_id =0,$order_status=0){ //General change of orderstatus $total = 1 ; if(empty($orders)){ $orders = array(); $orderslist = JRequest::getVar('orders', array()); $total = 0 ; // Get the list of orders in post to update foreach ($orderslist as $key => $order) { if ( $orderslist[$key]['order_status'] !== $orderslist[$key]['current_order_status'] ) { $orders[$key] = $orderslist[$key]; $total++; } } } if(!is_array($orders)){ $orders = array($orders); } /* Process the orders to update */ $updated = 0; $error = 0; if ($orders) { // $notify = JRequest::getVar('customer_notified', array()); // ??? // $comments = JRequest::getVar('comments', array()); // ??? foreach ($orders as $virtuemart_order_id => $order) { if ($order_id >0) $virtuemart_order_id= $order_id; $this->useDefaultEmailOrderStatus = false; if($this->updateStatusForOneOrder($virtuemart_order_id,$order)){ $updated ++; } else { $error++; } } } $result = array( 'updated' => $updated , 'error' =>$error , 'total' => $total ) ; return $result ; } // IMPORTANT: The $inputOrder can contain extra data by plugins //also strange $useTriggers is always activated? function updateStatusForOneOrder($virtuemart_order_id,$inputOrder,$useTriggers=true){ // vmdebug('updateStatusForOneOrder', $inputOrder); /* Update the order */ $data = $this->getTable('orders'); $data->load($virtuemart_order_id); $old_order_status = $data->order_status; $data->bind($inputOrder); $cp_rm = VmConfig::get('cp_rm',array('C')); if(!is_array($cp_rm)) $cp_rm = array($cp_rm); if ( in_array((string) $data->order_status,$cp_rm) ){ if (!empty($data->coupon_code)) { if (!class_exists('CouponHelper')) require(JPATH_VM_SITE . DS . 'helpers' . DS . 'coupon.php'); CouponHelper::RemoveCoupon($data->coupon_code); } } //First we must call the payment, the payment manipulates the result of the order_status if($useTriggers){ if(!class_exists('vmPSPlugin')) require(JPATH_VM_PLUGINS.DS.'vmpsplugin.php'); // Payment decides what to do when order status is updated JPluginHelper::importPlugin('vmcalculation'); JPluginHelper::importPlugin('vmcustom'); JPluginHelper::importPlugin('vmshipment'); JPluginHelper::importPlugin('vmpayment'); $_dispatcher = JDispatcher::getInstance(); //Should we add this? $inputOrder $_returnValues = $_dispatcher->trigger('plgVmOnUpdateOrderPayment',array(&$data,$old_order_status)); foreach ($_returnValues as $_returnValue) { if ($_returnValue === true) { break; // Plugin was successfull } elseif ($_returnValue === false) { return false; // Plugin failed } // Ignore null status and look for the next returnValue } $_dispatcher = JDispatcher::getInstance(); //Should we add this? $inputOrder $_returnValues = $_dispatcher->trigger('plgVmOnUpdateOrderShipment',array(&$data,$old_order_status)); /** * If an order gets cancelled, fire a plugin event, perhaps * some authorization needs to be voided */ if ($data->order_status == "X") { $_dispatcher = JDispatcher::getInstance(); //Should be renamed to plgVmOnCancelOrder $_dispatcher->trigger('plgVmOnCancelPayment',array(&$data,$old_order_status)); } } if(empty($data->delivery_date)){ $del_date_type = VmConfig::get('del_date_type','m'); if(strpos($del_date_type,'os')!==FALSE){ //for example osS $os = substr($del_date_type,2); if($data->order_status == $os){ $date = JFactory::getDate(); $data->delivery_date = $date->toMySQL(); } } else { VmConfig::loadJLang('com_virtuemart_orders', true); $data->delivery_date = JText::_('COM_VIRTUEMART_DELDATE_INV'); } } if ($data->store()) { $task= JRequest::getCmd('task',0); $view= JRequest::getWord('view',0); /*if($task=='edit'){ $update_lines = JRequest::getInt('update_lines'); } else /*/ if ($task=='updatestatus' and $view=='orders') { $lines = JRequest::getVar('orders'); $update_lines = $lines[$virtuemart_order_id]['update_lines']; } else { $update_lines = 1; } if($update_lines==1){ vmdebug('$update_lines '.$update_lines); $q = 'SELECT virtuemart_order_item_id FROM #__virtuemart_order_items WHERE virtuemart_order_id="'.$virtuemart_order_id.'"'; $db = JFactory::getDBO(); $db->setQuery($q); $order_items = $db->loadObjectList(); if ($order_items) { // vmdebug('updateStatusForOneOrder',$data); foreach ($order_items as $order_item) { //$this->updateSingleItem($order_item->virtuemart_order_item_id, $data->order_status, $order['comments'] , $virtuemart_order_id, $data->order_pass); $this->updateSingleItem($order_item->virtuemart_order_item_id, $data); } } } /* Update the order history */ $this->_updateOrderHist($virtuemart_order_id, $data->order_status, $inputOrder['customer_notified'], $inputOrder['comments']); // When the plugins did not already notified the user, do it here (the normal way) //Attention the ! prevents at the moment that an email is sent. But it should used that way. // if (!$inputOrder['customer_notified']) { $this->notifyCustomer( $data->virtuemart_order_id , $inputOrder ); // } JPluginHelper::importPlugin('vmcoupon'); $dispatcher = JDispatcher::getInstance(); $returnValues = $dispatcher->trigger('plgVmCouponUpdateOrderStatus', array($data, $old_order_status)); if(!empty($returnValues)){ foreach ($returnValues as $returnValue) { if ($returnValue !== null ) { return $returnValue; } } } return true; } else { return false; } } /** * Update an order status and send e-mail if needed * @author RolandD * @author Oscar van Eijk * @deprecated */ public function updateStatus( $orders=null,$virtuemart_order_id =0){ $this -> updateOrderStatus($orders,$virtuemart_order_id); return; } /** * Get the information from the cart and create an order from it * * @author Oscar van Eijk * @param object $_cart The cart data * @return mixed The new ordernumber, false on errors */ public function createOrderFromCart($cart) { if ($cart === null) { vmError('createOrderFromCart() called without a cart - that\'s a programming bug','Can\'t create order, sorry.'); return false; } $usr = JFactory::getUser(); $prices = $cart->getCartPrices(); if (($orderID = $this->_createOrder($cart, $usr, $prices)) == 0) { vmError('Couldn\'t create order','Couldn\'t create order'); return false; } if (!$this->_createOrderLines($orderID, $cart)) { vmError('Couldn\'t create order items','Couldn\'t create order items'); return false; } if (!$this-> _createOrderCalcRules($orderID, $cart) ) { vmError('Couldn\'t create order items','Couldn\'t create order items'); return false; } $this->_updateOrderHist($orderID); if (!$this->_writeUserInfo($orderID, $usr, $cart)) { vmError('Couldn\'t create order history','Couldn\'t create order history'); return false; } return $orderID; } /** * Write the order header record * * @author Oscar van Eijk * @param object $_cart The cart data * @param object $_usr User object * @param array $_prices Price data * @return integer The new ordernumber */ private function _createOrder($_cart, $_usr, $_prices) { // TODO We need tablefields for the new values: // Shipment: // $_prices['shipmentValue'] w/out tax // $_prices['shipmentTax'] Tax // $_prices['salesPriceShipment'] Total // // Payment: // $_prices['paymentValue'] w/out tax // $_prices['paymentTax'] Tax // $_prices['paymentDiscount'] Discount // $_prices['salesPricePayment'] Total $_orderData = new stdClass(); $_orderData->virtuemart_order_id = null; $_orderData->virtuemart_user_id = $_usr->get('id'); $_orderData->virtuemart_vendor_id = $_cart->vendorId; $_orderData->customer_number = $_cart->customer_number; //Note as long we do not have an extra table only storing addresses, the virtuemart_userinfo_id is not needed. //The virtuemart_userinfo_id is just the id of a stored address and is only necessary in the user maintance view or for choosing addresses. //the saved order should be an snapshot with plain data written in it. // $_orderData->virtuemart_userinfo_id = 'TODO'; // $_cart['BT']['virtuemart_userinfo_id']; // TODO; Add it in the cart... but where is this used? Obsolete? $_orderData->order_total = $_prices['billTotal']; $_orderData->order_salesPrice = $_prices['salesPrice']; $_orderData->order_billTaxAmount = $_prices['billTaxAmount']; $_orderData->order_billDiscountAmount = $_prices['billDiscountAmount']; $_orderData->order_discountAmount = $_prices['discountAmount']; $_orderData->order_subtotal = $_prices['priceWithoutTax']; $_orderData->order_tax = $_prices['taxAmount']; $_orderData->order_shipment = $_prices['shipmentValue']; $_orderData->order_shipment_tax = $_prices['shipmentTax']; $_orderData->order_payment = $_prices['paymentValue']; $_orderData->order_payment_tax = $_prices['paymentTax']; if (!empty($_cart->cartData['VatTax'])) { $taxes = array(); foreach($_cart->cartData['VatTax'] as $k=>$VatTax) { $taxes[$k]['virtuemart_calc_id'] = $k; $taxes[$k]['calc_name'] = $VatTax['calc_name']; $taxes[$k]['calc_value'] = $VatTax['calc_value']; $taxes[$k]['result'] = $VatTax['result']; } $_orderData->order_billTax = json_encode($taxes); } if (!empty($_cart->couponCode)) { $_orderData->coupon_code = $_cart->couponCode; $_orderData->coupon_discount = $_prices['salesPriceCoupon']; } $_orderData->order_discount = $_prices['discountAmount']; // discount order_items $_orderData->order_status = 'P'; $_orderData->order_currency = $this->getVendorCurrencyId($_orderData->virtuemart_vendor_id); if (isset($_cart->pricesCurrency)) { $_orderData->user_currency_id = $_cart->paymentCurrency ;//$this->getCurrencyIsoCode($_cart->pricesCurrency); $currency = CurrencyDisplay::getInstance($_orderData->user_currency_id); if($_orderData->user_currency_id != $_orderData->order_currency){ $_orderData->user_currency_rate = $currency->convertCurrencyTo($_orderData->user_currency_id ,1.0,false); } else { $_orderData->user_currency_rate=1.0; } } $_orderData->virtuemart_paymentmethod_id = $_cart->virtuemart_paymentmethod_id; $_orderData->virtuemart_shipmentmethod_id = $_cart->virtuemart_shipmentmethod_id; $_filter = JFilterInput::getInstance (array('br', 'i', 'em', 'b', 'strong'), array(), 0, 0, 1); $_orderData->customer_note = $_filter->clean($_cart->customer_comment); $_orderData->order_language = $_cart->order_language; $_orderData->ip_address = $_SERVER['REMOTE_ADDR']; $_orderData->order_number =''; JPluginHelper::importPlugin('vmshopper'); $dispatcher = JDispatcher::getInstance(); $plg_datas = $dispatcher->trigger('plgVmOnUserOrder',array(&$_orderData)); foreach($plg_datas as $plg_data){ // $data = array_merge($plg_data,$data); } if(empty($_orderData->order_number)){ $_orderData->order_number = $this->generateOrderNumber($_usr->get('id'),4,$_orderData->virtuemart_vendor_id); } if(empty($_orderData->order_pass)){ $_orderData->order_pass = 'p_'.substr( md5((string)time().rand(1,1000).$_orderData->order_number ), 0, 5); } $orderTable = $this->getTable('orders'); $orderTable -> bindChecknStore($_orderData); $errors = $orderTable->getErrors(); foreach($errors as $error){ vmError($error); } $db = JFactory::getDBO(); $_orderID = $db->insertid(); if (!empty($_cart->couponCode)) { //set the virtuemart_order_id in the Request for 3rd party coupon components (by Seyi and Max) JRequest::setVar ( 'virtuemart_order_id', $_orderData->virtuemart_order_id ); // If a gift coupon was used, remove it now //CouponHelper::RemoveCoupon($_cart->couponCode); CouponHelper::setInUseCoupon($_cart->couponCode, true); } // the order number is saved into the session to make sure that the correct cart is emptied with the payment notification $_cart->order_number=$_orderData->order_number; $_cart->setCartIntoSession (); return $_orderID; } private function getVendorCurrencyId($vendorId){ $q = 'SELECT `vendor_currency` FROM `#__virtuemart_vendors` WHERE `virtuemart_vendor_id`="'.$vendorId.'" '; $db = JFactory::getDBO(); $db->setQuery($q); $vendorCurrency = $db->loadResult(); return $vendorCurrency; // return $this->getCurrencyIsoCode($vendorCurrency); } private function getCurrencyIsoCode($vmCode){ $q = 'SELECT `currency_numeric_code` FROM `#__virtuemart_currencies` WHERE `virtuemart_currency_id`="'.$vmCode.'" '; $db = JFactory::getDBO(); $db->setQuery($q); return $db->loadResult(); } /** * Write the BillTo record, and if set, the ShipTo record * * @author Oscar van Eijk * @param integer $_id Order ID * @param object $_usr User object * @param object $_cart Cart object * @return boolean True on success */ private function _writeUserInfo($_id, &$_usr, $_cart) { $_userInfoData = array(); if(!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'userfields.php'); //if(!class_exists('shopFunctions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'shopfunctions.php'); $_userFieldsModel = VmModel::getModel('userfields'); $_userFieldsBT = $_userFieldsModel->getUserFields('account' , array('delimiters'=>true, 'captcha'=>true) , array('username', 'password', 'password2', 'user_is_vendor') ); foreach ($_userFieldsBT as $_fld) { $_name = $_fld->name; if(!empty( $_cart->BT[$_name])){ if (is_array( $_cart->BT[$_name])) { $_userInfoData[$_name] = implode("|*|",$_cart->BT[$_name]); } else { $_userInfoData[$_name] = $_cart->BT[$_name]; } } } $_userInfoData['virtuemart_order_id'] = $_id; $_userInfoData['virtuemart_user_id'] = $_usr->get('id'); $_userInfoData['address_type'] = 'BT'; $order_userinfosTable = $this->getTable('order_userinfos'); if (!$order_userinfosTable->bindChecknStore($_userInfoData)){ vmError($order_userinfosTable->getError()); return false; } if ($_cart->ST) { $_userInfoData = array(); // $_userInfoData['virtuemart_order_userinfo_id'] = null; // Reset key to make sure it doesn't get overwritten by ST $_userFieldsST = $_userFieldsModel->getUserFields('shipment' , array('delimiters'=>true, 'captcha'=>true) , array('username', 'password', 'password2', 'user_is_vendor') ); foreach ($_userFieldsST as $_fld) { $_name = $_fld->name; if(!empty( $_cart->ST[$_name])){ $_userInfoData[$_name] = $_cart->ST[$_name]; } } $_userInfoData['virtuemart_order_id'] = $_id; $_userInfoData['virtuemart_user_id'] = $_usr->get('id'); $_userInfoData['address_type'] = 'ST'; $order_userinfosTable = $this->getTable('order_userinfos'); if (!$order_userinfosTable->bindChecknStore($_userInfoData)){ vmError($order_userinfosTable->getError()); return false; } } return true; } function handleStockAfterStatusChangedPerProduct($newState, $oldState,$tableOrderItems, $quantity) { if($newState == $oldState) return; // $StatutWhiteList = array('P','C','X','R','S','N'); $db = JFactory::getDBO(); $db->setQuery('SELECT * FROM `#__virtuemart_orderstates` '); $StatutWhiteList = $db->loadAssocList('order_status_code'); // new product is statut N $StatutWhiteList['N'] = Array ( 'order_status_id' => 0 , 'order_status_code' => 'N' , 'order_stock_handle' => 'A'); if(!array_key_exists($oldState,$StatutWhiteList) or !array_key_exists($newState,$StatutWhiteList)) { vmError('The workflow for '.$newState.' or '.$oldState.' is unknown, take a look on model/orders function handleStockAfterStatusChanged','Can\'t process workflow, contact the shopowner. Status is'.$newState); return ; } //vmdebug( 'updatestock qt :' , $quantity.' id :'.$productId); // P Pending // C Confirmed // X Cancelled // R Refunded // S Shipped // N New or coming from cart // TO have no product setted as ordered when added to cart simply delete 'P' FROM array Reserved // don't set same values in the 2 arrays !!! // stockOut is in normal case shipped product //order_stock_handle // 'A' : stock Available // 'O' : stock Out // 'R' : stock reserved // the status decreasing real stock ? // $stockOut = array('S'); if ($StatutWhiteList[$newState]['order_stock_handle'] == 'O') $isOut = 1; else $isOut = 0; if ($StatutWhiteList[$oldState]['order_stock_handle'] == 'O') $wasOut = 1; else $wasOut = 0; // $isOut = in_array($newState, $stockOut); // $wasOut= in_array($oldState, $stockOut); // Stock change ? if ($isOut && !$wasOut) $product_in_stock = '-'; else if ($wasOut && !$isOut ) $product_in_stock = '+'; else $product_in_stock = '='; // the status increasing reserved stock(virtual Stock = product_in_stock - product_ordered) // $Reserved = array('P','C'); if ($StatutWhiteList[$newState]['order_stock_handle'] == 'R') $isReserved = 1; else $isReserved = 0; if ($StatutWhiteList[$oldState]['order_stock_handle'] == 'R') $wasReserved = 1; else $wasReserved = 0; // $isReserved = in_array($newState, $Reserved); // $wasReserved = in_array($oldState, $Reserved); // reserved stock must be change(all ordered product) if ($isReserved && !$wasReserved ) $product_ordered = '+'; else if (!$isReserved && $wasReserved ) $product_ordered = '-'; else $product_ordered = '='; //Here trigger plgVmGetProductStockToUpdateByCustom $productModel = VmModel::getModel('product'); if (!empty($tableOrderItems->product_attribute)) { if(!class_exists('VirtueMartModelCustomfields'))require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'customfields.php'); $virtuemart_product_id = $tableOrderItems->virtuemart_product_id; $product_attributes = json_decode($tableOrderItems->product_attribute,true); foreach ($product_attributes as $virtuemart_customfield_id=>$param){ if ($param) { if ($productCustom = VirtueMartModelCustomfields::getProductCustomField ($virtuemart_customfield_id ) ) { if ($productCustom->field_type == "E") { //$product = self::addParam($product); if(!class_exists('vmCustomPlugin')) require(JPATH_VM_PLUGINS.DS.'vmcustomplugin.php'); JPluginHelper::importPlugin('vmcustom'); $dispatcher = JDispatcher::getInstance(); //vmdebug('handleStockAfterStatusChangedPerProduct ',$param); $dispatcher->trigger('plgVmGetProductStockToUpdateByCustom',array(&$tableOrderItems,$param, $productCustom)); } } } } //vmdebug('produit',$product); // we can have more then one product in case of pack // in case of child, ID must be the child ID // TO DO use $prod->amount change for packs(eg. 1 computer and 2 HDD) if (is_array($tableOrderItems)) foreach ($tableOrderItems as $prod ) $productModel->updateStockInDB($prod, $quantity,$product_in_stock,$product_ordered); else $productModel->updateStockInDB($tableOrderItems, $quantity,$product_in_stock,$product_ordered); } else { $productModel->updateStockInDB ($tableOrderItems, $quantity,$product_in_stock,$product_ordered); } } /** * Create the ordered item records * * @author Oscar van Eijk * @author Kohl Patrick * @param integer $_id integer Order ID * @param object $_cart array The cart data * @return boolean True on success */ private function _createOrderLines($_id, $_cart) { $_orderItems = $this->getTable('order_items'); // $_lineCount = 0; foreach ($_cart->products as $priceKey=>$_prod) { if (!is_int($priceKey)) { if(!class_exists('calculationHelper')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'calculationh.php'); $calculator = calculationHelper::getInstance(); $variantmods = $calculator->parseModifier($priceKey); $row=0 ; //$product_id = (int)$priceKey; $_prod->product_attribute = ''; $product_attribute = array(); //MarkerVarMods //foreach($variantmods as $variant=>$selected){ foreach($variantmods as $selected=>$variant){ if ($selected) { if(!class_exists('VirtueMartModelCustomfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'customfields.php'); $productCustom = VirtueMartModelCustomfields::getProductCustomField ($selected ); //vmdebug('$_prod,$productCustom',$productCustom ); if ($productCustom->field_type == "E") { if(!class_exists('vmCustomPlugin')) require(JPATH_VM_PLUGINS.DS.'vmcustomplugin.php'); //We need something like this $product_attribute[$selected] = $productCustom->virtuemart_custom_id; //but seems we are forced to use this //$product_attribute[$selected] = $selected; if(!empty($_prod->param)){ foreach($_prod->param as $k => $plg){ if ($k == $selected){ //TODO productCartId $product_attribute[$selected] = $plg ; } } } } else { $product_attribute[$selected] = ' '.$productCustom->custom_title.''.$productCustom->custom_value.''; //$product_attribute[$variant] = ' '.$productCustom->custom_title.''.$productCustom->custom_value.''; } } $row++; } //if (isset($_prod->userfield )) $_prod->product_attribute .= '
'.$_prod->userfield.' : '; $_orderItems->product_attribute = json_encode($product_attribute); //print_r($product_attribute); } else { $_orderItems->product_attribute = null ; } // TODO: add fields for the following data: // * [double] basePrice = 38.48 // * [double] basePriceVariant = 38.48 // * [double] basePriceWithTax = 42.04 // * [double] discountedPriceWithoutTax = 36.48 // * [double] priceBeforeTax = 36.48 // * [double] salesPrice = 39.85 // * [double] salesPriceTemp = 39.85 // * [double] taxAmount = 3.37 // * [double] salesPriceWithDiscount = 0 // * [double] discountAmount = 2.19 // * [double] priceWithoutTax = 36.48 // * [double] variantModification = 0 $_orderItems->virtuemart_order_item_id = null; $_orderItems->virtuemart_order_id = $_id; // $_orderItems->virtuemart_userinfo_id = 'TODO'; //$_cart['BT']['virtuemart_userinfo_id']; // TODO; Add it in the cart... but where is this used? Obsolete? $_orderItems->virtuemart_vendor_id = $_prod->virtuemart_vendor_id; $_orderItems->virtuemart_product_id = $_prod->virtuemart_product_id; $_orderItems->order_item_sku = $_prod->product_sku; $_orderItems->order_item_name = $_prod->product_name; //TODO Patrick $_orderItems->product_quantity = $_prod->quantity; $_orderItems->product_item_price = $_cart->pricesUnformatted[$priceKey]['basePrice']; $_orderItems->product_basePriceWithTax = $_cart->pricesUnformatted[$priceKey]['basePriceWithTax']; $_orderItems->product_priceWithoutTax = $_cart->pricesUnformatted[$priceKey]['priceWithoutTax']; $_orderItems->product_discountedPriceWithoutTax = $_cart->pricesUnformatted[$priceKey]['discountedPriceWithoutTax']; //$_orderItems->product_tax = $_cart->pricesUnformatted[$priceKey]['subtotal_tax_amount']; $_orderItems->product_tax = $_cart->pricesUnformatted[$priceKey]['taxAmount']; $_orderItems->product_final_price = $_cart->pricesUnformatted[$priceKey]['salesPrice']; $_orderItems->product_subtotal_discount = $_cart->pricesUnformatted[$priceKey]['subtotal_discount']; $_orderItems->product_subtotal_with_tax = $_cart->pricesUnformatted[$priceKey]['subtotal_with_tax']; // $_orderItems->order_item_currency = $_prices[$_lineCount]['']; // TODO Currency $_orderItems->order_status = 'P'; if (!$_orderItems->check()) { vmError($this->getError()); return false; } // Save the record to the database if (!$_orderItems->store()) { vmError($this->getError()); return false; } $_prod->virtuemart_order_item_id = $_orderItems->virtuemart_order_item_id; // vmdebug('_createOrderLines',$_prod); $this->handleStockAfterStatusChangedPerProduct( $_orderItems->order_status,'N',$_orderItems,$_orderItems->product_quantity); } //jExit(); return true; } /** * Create the ordered item records * * @author Valerie Isaksen * @param integer $_id integer Order ID * @param object $_cart array The cart data * @return boolean True on success */ private function _createOrderCalcRules($order_id, $_cart) { $productKeys = array_keys($_cart->products); $calculation_kinds = array('DBTax','Tax','VatTax','DATax'); foreach($productKeys as $key){ foreach($calculation_kinds as $calculation_kind) { if(!isset($_cart->pricesUnformatted[$key][$calculation_kind])) continue; $productRules = $_cart->pricesUnformatted[$key][$calculation_kind]; foreach($productRules as $rule){ $orderCalcRules = $this->getTable('order_calc_rules'); $orderCalcRules->virtuemart_order_calc_rule_id= null; $orderCalcRules->virtuemart_calc_id= $rule[7]; $orderCalcRules->virtuemart_order_item_id = $_cart->products[$key]->virtuemart_order_item_id; $orderCalcRules->calc_rule_name = $rule[0]; $orderCalcRules->calc_amount = 0; $orderCalcRules->calc_result = 0; if ($calculation_kind == 'VatTax') { $orderCalcRules->calc_amount = $_cart->pricesUnformatted[$key]['taxAmount']; $orderCalcRules->calc_result = $_cart->cartData['VatTax'][$rule[7]]['result']; } $orderCalcRules->calc_value = $rule[1]; $orderCalcRules->calc_mathop = $rule[2]; $orderCalcRules->calc_kind = $calculation_kind; $orderCalcRules->calc_currency = $rule[4]; $orderCalcRules->calc_params = $rule[5]; $orderCalcRules->virtuemart_vendor_id = $rule[6]; $orderCalcRules->virtuemart_order_id = $order_id; if (!$orderCalcRules->check()) { vmError('_createOrderCalcRules check product rule '.$this->getError()); vmdebug('_createOrderCalcRules check product rule '.$this->getError()); return false; } // Save the record to the database if (!$orderCalcRules->store()) { vmError('_createOrderCalcRules store product rule '.$this->getError()); vmdebug('_createOrderCalcRules store product rule '.$this->getError()); return false; } } } } $Bill_calculation_kinds=array('DBTaxRulesBill', 'taxRulesBill', 'DATaxRulesBill'); // vmdebug('_createOrderCalcRules',$_cart ); foreach($Bill_calculation_kinds as $calculation_kind) { // if(empty($_cart->cartData)){ // vmError('Cart data was empty, why?'); // if(!class_exists('calculationHelper')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'calculationh.php'); // $calculator = calculationHelper::getInstance(); // $_cart->cartData = $calculator->getCartData(); // } foreach($_cart->cartData[$calculation_kind] as $rule){ $orderCalcRules = $this->getTable('order_calc_rules'); $orderCalcRules->virtuemart_order_calc_rule_id = null; $orderCalcRules->virtuemart_calc_id= $rule['virtuemart_calc_id']; $orderCalcRules->calc_rule_name= $rule['calc_name']; $orderCalcRules->calc_amount = $_cart->pricesUnformatted[$rule['virtuemart_calc_id'].'Diff']; if ($calculation_kind == 'taxRulesBill' and !empty($_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['result'])) { $orderCalcRules->calc_result = $_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['result']; } $orderCalcRules->calc_kind=$calculation_kind; $orderCalcRules->calc_mathop=$rule['calc_value_mathop']; $orderCalcRules->virtuemart_order_id=$order_id; $orderCalcRules->calc_params=$rule['calc_params']; if (!$orderCalcRules->check()) { vmError('_createOrderCalcRules store bill rule '.$this->getError()); return false; } // Save the record to the database if (!$orderCalcRules->store()) { vmError('_createOrderCalcRules store bill rule '.$this->getError()); return false; } } } if(!empty($_cart->virtuemart_paymentmethod_id)){ $orderCalcRules = $this->getTable('order_calc_rules'); $calcModel = VmModel::getModel('calc'); $calcModel->setId($_cart->pricesUnformatted['payment_calc_id']); $calc = $calcModel->getCalc(); $orderCalcRules->virtuemart_order_calc_rule_id = null; $orderCalcRules->virtuemart_calc_id = $calc->virtuemart_calc_id; $orderCalcRules->calc_kind = 'payment'; $orderCalcRules->calc_rule_name = $calc->calc_name; $orderCalcRules->calc_amount = $_cart->pricesUnformatted['paymentTax']; $orderCalcRules->calc_value = $calc->calc_value; $orderCalcRules->calc_mathop = $calc->calc_value_mathop; $orderCalcRules->calc_currency = $calc->calc_currency; $orderCalcRules->calc_params = $calc->calc_params; $orderCalcRules->virtuemart_vendor_id = $calc->virtuemart_vendor_id; $orderCalcRules->virtuemart_order_id = $order_id; if (!$orderCalcRules->check()) { vmError('_createOrderCalcRules store payment rule '.$this->getError()); return false; } // Save the record to the database if (!$orderCalcRules->store()) { vmError('_createOrderCalcRules store payment rule '.$this->getError()); return false; } } if(!empty($_cart->virtuemart_shipmentmethod_id)){ $orderCalcRules = $this->getTable('order_calc_rules'); $calcModel = VmModel::getModel('calc'); $calcModel->setId($_cart->pricesUnformatted['shipment_calc_id']); $calc = $calcModel->getCalc(); $orderCalcRules->virtuemart_order_calc_rule_id = null; $orderCalcRules->virtuemart_calc_id = $calc->virtuemart_calc_id; $orderCalcRules->calc_kind = 'shipment'; $orderCalcRules->calc_rule_name = $calc->calc_name; $orderCalcRules->calc_amount = $_cart->pricesUnformatted['shipmentTax']; $orderCalcRules->calc_value = $calc->calc_value; $orderCalcRules->calc_mathop = $calc->calc_value_mathop; $orderCalcRules->calc_currency = $calc->calc_currency; $orderCalcRules->calc_params = $calc->calc_params; $orderCalcRules->virtuemart_vendor_id = $calc->virtuemart_vendor_id; $orderCalcRules->virtuemart_order_id = $order_id; if (!$orderCalcRules->check()) { vmError('_createOrderCalcRules store shipment rule '.$this->getError()); return false; } // Save the record to the database if (!$orderCalcRules->store()) { vmError('_createOrderCalcRules store shipment rule '.$this->getError()); return false; } } //jExit(); return true; } /** * Update the order history * * @author Oscar van Eijk * @param $_id Order ID * @param $_status New order status (default: P) * @param $_notified 1 (default) if the customer was notified, 0 otherwise * @param $_comment (Customer) comment, default empty */ public function _updateOrderHist($_id, $_status = 'P', $_notified = 0, $_comment = '') { $_orderHist = $this->getTable('order_histories'); $_orderHist->virtuemart_order_id = $_id; $_orderHist->order_status_code = $_status; //$_orderHist->date_added = date('Y-m-d G:i:s', time()); $_orderHist->customer_notified = $_notified; $_orderHist->comments = nl2br($_comment); $_orderHist->store(); } /** * Update the order item history * * @author Oscar van Eijk,kohl patrick * @param $_id Order ID * @param $_status New order status (default: P) * @param $_notified 1 (default) if the customer was notified, 0 otherwise * @param $_comment (Customer) comment, default empty */ private function _updateOrderItemHist($_id, $status = 'P', $notified = 1, $comment = '') { $_orderHist = $this->getTable('order_item_histories'); $_orderHist->virtuemart_order_item_id = $_id; $_orderHist->order_status_code = $status; $_orderHist->customer_notified = $notified; $_orderHist->comments = $comment; $_orderHist->store(); } /** * Generate a unique ordernumber. This is done in a similar way as VM1.1.x, although * the reason for this is unclear to me :-S * * @author Oscar van Eijk * @param integer $uid The user ID. Defaults to 0 for guests * @return string A unique ordernumber */ static public function generateOrderNumber($uid = 0,$length=10, $virtuemart_vendor_id=1) { $db = JFactory::getDBO(); $q = 'SELECT COUNT(1) FROM #__virtuemart_orders WHERE `virtuemart_vendor_id`="'.$virtuemart_vendor_id.'"'; $db->setQuery($q); //We can use that here, because the order_number is free to set, the invoice_number must often follow special rules $count = $db->loadResult(); $count = $count + (int)VM_ORDER_OFFSET; // vmdebug('my db creating ordernumber VM_ORDER_OFFSET '.VM_ORDER_OFFSET.' $count '.$count, $this->_db); // $variable_fixed=sprintf("%06s",$num_rows); $data = substr( md5( session_id().(string)time().(string)$uid ) ,0 ,$length ).'0'.$count; return $data; } /* * returns true if an invoice number has been created * returns false if an invoice number has not been created due to some configuration parameters */ function createInvoiceNumber($orderDetails, &$invoiceNumber){ $orderDetails = (array)$orderDetails; $db = JFactory::getDBO(); if(!isset($orderDetails['virtuemart_order_id'])){ vmWarn('createInvoiceNumber $orderDetails has no virtuemart_order_id ',$orderDetails); vmdebug('createInvoiceNumber $orderDetails has no virtuemart_order_id ',$orderDetails); } $q = 'SELECT * FROM `#__virtuemart_invoices` WHERE `virtuemart_order_id`= "'.$orderDetails['virtuemart_order_id'].'" '; // AND `order_status` = "'.$orderDetails->order_status.'" '; $db->setQuery($q); $result = $db->loadAssoc(); // vmdebug('my createInvoiceNumber $q '.$q,$result); if (!class_exists('ShopFunctions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'shopfunctions.php'); if(!$result or empty($result['invoice_number']) ){ $data['virtuemart_order_id'] = $orderDetails['virtuemart_order_id']; $data['order_status'] = $orderDetails['order_status']; $data['virtuemart_vendor_id'] = $orderDetails['virtuemart_vendor_id']; JPluginHelper::importPlugin('vmshopper'); JPluginHelper::importPlugin('vmpayment'); $dispatcher = JDispatcher::getInstance(); // plugin returns invoice number, 0 if it does not want an invoice number to be created by Vm $plg_datas = $dispatcher->trigger('plgVmOnUserInvoice',array($orderDetails,&$data)); foreach($plg_datas as $plg_data){ // $data = array_merge($plg_data,$data); } if(!isset($data['invoice_number']) ) { // check the default configuration $orderstatusForInvoice = VmConfig::get('inv_os',array('C')); if(!is_array($orderstatusForInvoice)) $orderstatusForInvoice = array($orderstatusForInvoice); //for backward compatibility 2.0.8e $pdfInvoice = (int)VmConfig::get('pdf_invoice', 0); // backwards compatible $force_create_invoice=JRequest::getInt('create_invoice', 0); // florian : added if pdf invoice are enabled if ( in_array($orderDetails['order_status'],$orderstatusForInvoice) or $pdfInvoice==1 or $force_create_invoice==1 ){ $q = 'SELECT COUNT(1) FROM `#__virtuemart_invoices` WHERE `virtuemart_vendor_id`= "'.$orderDetails['virtuemart_vendor_id'].'" '; // AND `order_status` = "'.$orderDetails->order_status.'" '; $db->setQuery($q); $count = $db->loadResult()+1; if(empty($data['invoice_number'])) { //$variable_fixed=sprintf("%05s",$num_rows); $date = date("Y-m-d"); // $date = JFactory::getDate()->toMySQL(); $data['invoice_number'] = str_replace('-', '', substr($date,2,8)).substr(md5($orderDetails['order_number'].$orderDetails['order_status']),0,3).'0'.$count; } } else { return false; } } $table = $this->getTable('invoices'); $table->bindChecknStore($data); $invoiceNumber= array($table->invoice_number,$table->created_on); } elseif (ShopFunctions::InvoiceNumberReserved($result['invoice_number']) ) { $invoiceNumber = array($result['invoice_number'],$result['created_on']); return true; } else { $invoiceNumber = array($result['invoice_number'],$result['created_on']); } return true; } /* * @author Valérie Isaksen */ function getInvoiceNumber($virtuemart_order_id){ $db = JFactory::getDBO(); $q = 'SELECT `invoice_number` FROM `#__virtuemart_invoices` WHERE `virtuemart_order_id`= "'.$virtuemart_order_id.'" '; $db->setQuery($q); return $db->loadresult(); } /** * Notifies the customer that the Order Status has been changed * * @author RolandD, Christopher Roussel, Valérie Isaksen, Max Milbers * */ private function notifyCustomer($virtuemart_order_id, $newOrderData = 0 ) { // vmdebug('notifyCustomer', $newOrderData); if (isset($newOrderData['customer_notified']) && $newOrderData['customer_notified']==0) { return true; } if(!class_exists('shopFunctionsF')) require(JPATH_VM_SITE.DS.'helpers'.DS.'shopfunctionsf.php'); //Important, the data of the order update mails, payments and invoice should //always be in the database, so using getOrder is the right method $orderModel=VmModel::getModel('orders'); $order = $orderModel->getOrder($virtuemart_order_id); $payment_name = $shipment_name=''; if (!class_exists('vmPSPlugin')) require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'); JPluginHelper::importPlugin('vmshipment'); JPluginHelper::importPlugin('vmpayment'); $dispatcher = JDispatcher::getInstance(); $returnValues = $dispatcher->trigger('plgVmOnShowOrderFEShipment',array( $order['details']['BT']->virtuemart_order_id, $order['details']['BT']->virtuemart_shipmentmethod_id, &$shipment_name)); $returnValues = $dispatcher->trigger('plgVmOnShowOrderFEPayment',array( $order['details']['BT']->virtuemart_order_id, $order['details']['BT']->virtuemart_paymentmethod_id, &$payment_name)); $order['shipmentName']=$shipment_name; $order['paymentName']=$payment_name; if($newOrderData!=0){ //We do not really need that $vars['newOrderData'] = (array)$newOrderData; } $vars['orderDetails']=$order; //$vars['includeComments'] = JRequest::getVar('customer_notified', array()); //I think this is misleading, I think it should always ask for example $vars['newOrderData']['doVendor'] directly //Using this function garantue us that it is always there. If the vendor should be informed should be done by the plugins //We may add later something to the method, defining this better $vars['url'] = 'url'; if(!isset($newOrderData['doVendor'])) $vars['doVendor'] = false; else $vars['doVendor'] = $newOrderData['doVendor']; $virtuemart_vendor_id=1; $vendorModel = VmModel::getModel('vendor'); $vendor = $vendorModel->getVendor($virtuemart_vendor_id); $vars['vendor'] = $vendor; $vendorEmail = $vendorModel->getVendorEmail($virtuemart_vendor_id); $vars['vendorEmail'] = $vendorEmail; /* $path = VmConfig::get('forSale_path',0); $orderstatusForInvoice = VmConfig::get('inv_os','C'); $pdfInvoice = VmConfig::get('pdf_invoice', 1); // backwards compatible */ // florian : added if pdf invoice are enabled //if ($this->getInvoiceNumber( $order['details']['BT']->virtuemart_order_id ) ){ $invoiceNumberDate = array(); if ($orderModel->createInvoiceNumber($order['details']['BT'], $invoiceNumberDate )) { $orderstatusForInvoice = VmConfig::get('inv_os',array('C')); if(!is_array($orderstatusForInvoice)) $orderstatusForInvoice = array($orderstatusForInvoice); // for backward compatibility 2.0.8e $pdfInvoice = (int)VmConfig::get('pdf_invoice', 0); // backwards compatible $force_create_invoice=JRequest::getInt('create_invoice', 0); //TODO we need an array of orderstatus if ( (in_array($order['details']['BT']->order_status,$orderstatusForInvoice)) or $pdfInvoice==1 or $force_create_invoice==1 ){ if (!shopFunctions::InvoiceNumberReserved($invoiceNumberDate[0])) { if(!class_exists('VirtueMartControllerInvoice')) require( JPATH_VM_SITE.DS.'controllers'.DS.'invoice.php' ); $controller = new VirtueMartControllerInvoice( array( 'model_path' => JPATH_VM_SITE.DS.'models', 'view_path' => JPATH_VM_SITE.DS.'views' )); $vars['mediaToSend'][] = $controller->getInvoicePDF($order); } } } // Send the email $res = shopFunctionsF::renderMail('invoice', $order['details']['BT']->email, $vars, null,$vars['doVendor'],$this->useDefaultEmailOrderStatus); if(is_object($res) or !$res){ $string = 'COM_VIRTUEMART_NOTIFY_CUSTOMER_ERR_SEND'; vmdebug('notifyCustomer function shopFunctionsF::renderMail throws JException'); $res = 0; } //We need this, to prevent that a false alert is thrown. else if ($res and $res!=-1) { $string = 'COM_VIRTUEMART_NOTIFY_CUSTOMER_SEND_MSG'; } if($res!=-1){ vmInfo( JText::_($string,false).' '.$order['details']['BT']->first_name.' '.$order['details']['BT']->last_name. ', '.$order['details']['BT']->email); } return true; } /** * Retrieve the details for an order line item. * * @author RickG * @param string $orderId Order id number * @param string $orderLineId Order line item number * @return object Object containing the order item details. */ function getOrderLineDetails($orderId, $orderLineId) { $table = $this->getTable('order_items'); if ($table->load((int)$orderLineId)) { return $table; } else { $table->reset(); $table->virtuemart_order_id = $orderId; return $table; } } /** * Save an order line item. * * @author RickG * @return boolean True of remove was successful, false otherwise */ function saveOrderLineItem($data) { $table = $this->getTable('order_items'); //Done in the table already /* $curDate = JFactory::getDate(); $data['modified_on'] = $curDate->toMySql();*/ if (!class_exists('vmPSPlugin')) require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'); JPluginHelper::importPlugin('vmshipment'); $_dispatcher = JDispatcher::getInstance(); $_returnValues = $_dispatcher->trigger('plgVmOnUpdateOrderLineShipment',array( $data)); foreach ($_returnValues as $_retVal) { if ($_retVal === false) { // Stop as soon as the first active plugin returned a failure status return; } } if (!class_exists('vmPSPlugin')) require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'); JPluginHelper::importPlugin('vmpayment'); $_returnValues = $_dispatcher->trigger('plgVmOnUpdateOrderLinePayment',array( $data)); foreach ($_returnValues as $_retVal) { if ($_retVal === false) { // Stop as soon as the first active plugin returned a failure status return; } } $table->bindChecknStore($data); return true; // return true; } /* *remove product from order item table *@var $virtuemart_order_id Order to clear */ function removeOrderItems ($virtuemart_order_id){ $q ='DELETE from `#__virtuemart_order_items` WHERE `virtuemart_order_id` = ' .(int) $virtuemart_order_id; $this->_db->setQuery($q); if ($this->_db->query() === false) { vmError($this->_db->getError()); return false; } return true; } /** * Remove an order line item. * * @author RickG * @param string $orderLineId Order line item number * @return boolean True of remove was successful, false otherwise */ function removeOrderLineItem($orderLineId) { $item = $this->getTable('order_items'); if (!$item->load($orderLineId)) { vmError($item->getError()); return false; } //TODO Why should the stock change, when the order is deleted? Paypal? Valerie? // $this->handleStockAfterStatusChangedPerProduct('C', $item->order_status,$item, $item->product_quantity); if ($item->delete($orderLineId)) { return true; } else { vmError($item->getError()); return false; } } /** * Delete all record ids selected * * @author Max Milbers * @author Patrick Kohl * @return boolean True is the delete was successful, false otherwise. */ public function remove($ids) { $table = $this->getTable($this->_maintablename); foreach($ids as $id) { // remove order_item and update stock $q = "SELECT `virtuemart_order_item_id` FROM `#__virtuemart_order_items` WHERE `virtuemart_order_id`=".$id; $this->_db->setQuery($q); $item_ids = $this->_db->loadResultArray(); foreach( $item_ids as $item_id ) { $this->removeOrderLineItem($item_id); } // rename invoice number by adding the date, and update the invoice table $this->renameInvoice($id ); if (!$table->delete((int)$id)) { vmError(get_class( $this ).'::remove '.$id.' '.$table->getError()); return false; } } return true; } /** Update order head record * * @author Ondřej Spilka * @author Maik Künnemann * @return boolean True is the update was successful, otherwise false. */ public function UpdateOrderHead($virtuemart_order_id, $_orderData) { $orderTable = $this->getTable('orders'); $orderTable->load($virtuemart_order_id); if (!$orderTable->bindChecknStore($_orderData, true)){ vmError($orderTable->getError()); return false; } $_userInfoData = array(); if(!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'userfields.php'); $_userFieldsModel = VmModel::getModel('userfields'); //bill to $_userFieldsBT = $_userFieldsModel->getUserFields('account' , array('delimiters'=>true, 'captcha'=>true) , array('username', 'password', 'password2', 'user_is_vendor') ); foreach ($_userFieldsBT as $_fld) { $_name = $_fld->name; if(isset( $_orderData["BT_{$_name}"])){ $_userInfoData[$_name] = $_orderData["BT_{$_name}"]; } } $_userInfoData['virtuemart_order_id'] = $virtuemart_order_id; $_userInfoData['address_type'] = 'BT'; $order_userinfosTable = $this->getTable('order_userinfos'); $order_userinfosTable->load($virtuemart_order_id, 'virtuemart_order_id'," AND address_type='BT'"); if (!$order_userinfosTable->bindChecknStore($_userInfoData, true)){ vmError($order_userinfosTable->getError()); return false; } //ship to $_userFieldsST = $_userFieldsModel->getUserFields('account' , array('delimiters'=>true, 'captcha'=>true) , array('username', 'password', 'password2', 'user_is_vendor') ); $_userInfoData = array(); foreach ($_userFieldsST as $_fld) { $_name = $_fld->name; if(isset( $_orderData["ST_{$_name}"])){ $_userInfoData[$_name] = $_orderData["ST_{$_name}"]; } } $_userInfoData['virtuemart_order_id'] = $virtuemart_order_id; $_userInfoData['address_type'] = 'ST'; $order_userinfosTable = $this->getTable('order_userinfos'); $order_userinfosTable->load($virtuemart_order_id, 'virtuemart_order_id'," AND address_type='ST'"); if (!$order_userinfosTable->bindChecknStore($_userInfoData, true)){ vmError($order_userinfosTable->getError()); return false; } $orderModel = VmModel::getModel('orders'); $order = $orderModel->getOrder($virtuemart_order_id); $dispatcher = JDispatcher::getInstance(); if (!class_exists ('CurrencyDisplay')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'); } // Update Payment Method if($_orderData['old_virtuemart_paymentmethod_id'] != $_orderData['virtuemart_paymentmethod_id']) { $this->_db->setQuery( 'SELECT `payment_element` FROM `#__virtuemart_paymentmethods` , `#__virtuemart_orders` WHERE `#__virtuemart_paymentmethods`.`virtuemart_paymentmethod_id` = `#__virtuemart_orders`.`virtuemart_paymentmethod_id` AND `virtuemart_order_id` = ' . $virtuemart_order_id ); $paymentTable = '#__virtuemart_payment_plg_'. $this->_db->loadResult(); $this->_db->setQuery("DELETE from `". $paymentTable ."` WHERE `virtuemart_order_id` = " . $virtuemart_order_id); if ($this->_db->query() === false) { vmError($this->_db->getError()); return false; } else { JPluginHelper::importPlugin('vmpayment'); } } // Update Shipment Method if($_orderData['old_virtuemart_shipmentmethod_id'] != $_orderData['virtuemart_shipmentmethod_id']) { $this->_db->setQuery( 'SELECT `shipment_element` FROM `#__virtuemart_shipmentmethods` , `#__virtuemart_orders` WHERE `#__virtuemart_shipmentmethods`.`virtuemart_shipmentmethod_id` = `#__virtuemart_orders`.`virtuemart_shipmentmethod_id` AND `virtuemart_order_id` = ' . $virtuemart_order_id ); $shipmentTable = '#__virtuemart_shipment_plg_'. $this->_db->loadResult(); $this->_db->setQuery("DELETE from `". $shipmentTable ."` WHERE `virtuemart_order_id` = " . $virtuemart_order_id); if ($this->_db->query() === false) { vmError($this->_db->getError()); return false; } else { JPluginHelper::importPlugin('vmshipment'); } } // JPluginHelper::importPlugin('vmshipment'); // JPluginHelper::importPlugin('vmcustom'); if (!class_exists('VirtueMartCart')) require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); $cart = VirtueMartCart::getCart(); $cart->virtuemart_paymentmethod_id = $_orderData['virtuemart_paymentmethod_id']; $cart->virtuemart_shipmentmethod_id = $_orderData['virtuemart_shipmentmethod_id']; $order['order_status'] = $order['details']['BT']->order_status; $order['customer_notified'] = 0; $order['comments'] = ''; $returnValues = $dispatcher->trigger('plgVmConfirmedOrder', array($cart, $order)); return true; } /** Create empty order head record from admin only * * @author Ondřej Spilka * @return ID of the newly created order */ public function CreateOrderHead() { // TODO // multivendor //usrid $usrid = 0; $_orderData = new stdClass(); $_orderData->virtuemart_order_id = null; $_orderData->virtuemart_user_id = 0; $_orderData->virtuemart_vendor_id = 1; //TODO $_orderData->order_total = 0; $_orderData->order_salesPrice = 0; $_orderData->order_billTaxAmount = 0; $_orderData->order_billDiscountAmount = 0; $_orderData->order_discountAmount = 0; $_orderData->order_subtotal = 0; $_orderData->order_tax = 0; $_orderData->order_shipment = 0; $_orderData->order_shipment_tax = 0; $_orderData->order_payment = 0; $_orderData->order_payment_tax = 0; $_orderData->order_discount = 0; $_orderData->order_status = 'P'; $_orderData->order_currency = $this->getVendorCurrencyId($_orderData->virtuemart_vendor_id); $_orderData->virtuemart_paymentmethod_id = JRequest::getInt('virtuemart_paymentmethod_id'); $_orderData->virtuemart_shipmentmethod_id = JRequest::getInt('virtuemart_shipmentmethod_id'); $_orderData->customer_note = ''; $_orderData->ip_address = $_SERVER['REMOTE_ADDR']; $_orderData->order_number =''; JPluginHelper::importPlugin('vmshopper'); $dispatcher = JDispatcher::getInstance(); $_orderData->order_number = $this->generateOrderNumber($usrid,4,$_orderData->virtuemart_vendor_id); $_orderData->order_pass = 'p_'.substr( md5((string)time().rand(1,1000).$_orderData->order_number ), 0, 5); $orderTable = $this->getTable('orders'); $orderTable -> bindChecknStore($_orderData); $errors = $orderTable->getErrors(); foreach($errors as $error){ vmError($error); } $db = JFactory::getDBO(); $_orderID = $db->insertid(); $_usr = JFactory::getUser(); if (!$this->_writeUserInfo($_orderID, $_usr, array())) { vmError($error); } $orderModel = VmModel::getModel('orders'); $order= $orderModel->getOrder($_orderID); $dispatcher = JDispatcher::getInstance(); JPluginHelper::importPlugin('vmcustom'); JPluginHelper::importPlugin('vmshipment'); JPluginHelper::importPlugin('vmpayment'); if (!class_exists('VirtueMartCart')) require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); $cart = VirtueMartCart::getCart(); $returnValues = $dispatcher->trigger('plgVmConfirmedOrder', array($cart, $order)); return $_orderID; } /** Rename Invoice (when an order is deleted) * * @author Valérie Isaksen * @param $order_id Id of the order * @return boolean true if deleted successful, false if there was a problem */ function renameInvoice($order_id ) { $db = JFactory::getDBO(); $q = 'SELECT * FROM `#__virtuemart_invoices` WHERE `virtuemart_order_id`= "'.$order_id.'" '; $db->setQuery($q); $data = $db->loadAssoc(); if(!$data or empty($data['invoice_number']) ){ return true; } // rename invoice pdf file $invoice_prefix='vminvoice_'; $path = shopFunctions::getInvoicePath(VmConfig::get('forSale_path',0)); $invoice_name_src = $path.DS.$invoice_prefix.$data['invoice_number'].'.pdf'; if(!file_exists($invoice_name_src)){ // may be it was already deleted when changing order items $data['invoice_number'] = $data['invoice_number'].' not found.'; } else { $date = date("Ymd"); $data['invoice_number'] = $data['invoice_number'].'_'.$date; $invoice_name_dst = $path.DS.$data['invoice_number'].'.pdf'; if(!class_exists('JFile')) require(JPATH_VM_LIBRARIES.DS.'joomla'.DS.'filesystem'.DS.'file.php'); if (!JFile::move($invoice_name_src, $invoice_name_dst)) { vmError ('Could not rename Invoice '.$invoice_name_src.'to '. $invoice_name_dst ); } } $table = $this->getTable('invoices'); $table->bindChecknStore($data); return true; } /** Delete Invoice when an item is updated * * @author Valérie Isaksen * @param $order_id Id of the order * @return boolean true if deleted successful, false if there was a problem */ function deleteInvoice($order_id ) { $db = JFactory::getDBO(); $q = 'SELECT * FROM `#__virtuemart_invoices` WHERE `virtuemart_order_id`= "'.$order_id.'" '; $db->setQuery($q); $data = $db->loadAssoc(); if(!$data or empty($data['invoice_number']) ){ return true; } // rename invoice pdf file $invoice_prefix='vminvoice_'; $path = shopFunctions::getInvoicePath(VmConfig::get('forSale_path',0)); $invoice_name_src = $path.DS.$invoice_prefix.$data['invoice_number'].'.pdf'; if(!file_exists($invoice_name_src)){ // was already deleted by a previoous change return; } if(!class_exists('JFile')) require(JPATH_VM_LIBRARIES.DS.'joomla'.DS.'filesystem'.DS.'file.php'); if (!JFile::delete($invoice_name_src )) { vmError ('Could not delete Invoice '.$invoice_name_src ); } } } // No closing tag fields/vendor.php000066600000003624151372127700010036 0ustar00element['key_field'] ? $this->element['key_field'] : 'value'); $val = ($this->element['value_field'] ? $this->element['value_field'] : $this->name); $model = VmModel::getModel('vendor'); $vendors = $model->getVendors(true, true, false); return JHTML::_('select.genericlist', $vendors, $this->name, 'class="inputbox" size="1"', 'virtuemart_vendor_id', 'vendor_name', $this->value, $this->id); } }fields/product.php000066600000003441151372127700010216 0ustar00element['key_field'] ? $this->element['key_field'] : 'value'); $val = ($this->element['value_field'] ? $this->element['value_field'] : $this->name); return JHTML::_('select.genericlist', $this->_getProducts(), $this->name, 'class="inputbox" ', 'value', 'text', $this->value, $this->id); } private function _getProducts() { if (!class_exists('VmModel')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'vmmodel.php'); $productModel = VmModel::getModel('Product'); $productModel->_noLimit = true; $products = $productModel->getProductListing(false, false, false, false, true,false); $productModel->_noLimit = false; $i = 0; $list = array(); foreach ($products as $product) { $list[$i]['value'] = $product->virtuemart_product_id; $list[$i]['text'] = $product->product_name. " (". $product->product_sku.")"; $i++; } return $list; } }fields/layout.php000066600000003450151372127700010053 0ustar00fieldname,0,-6);; $vmLayoutList =VirtueMartModelConfig::getLayoutList($view); $html = JHTML::_('Select.genericlist',$vmLayoutList, $this->name, 'size=1 width=200', 'value', 'text', array($this->value)); return $html; } }fields/manufacturer.php000066600000003267151372127700011240 0ustar00element['key_field'] ? $this->element['key_field'] : 'value'); $val = ($this->element['value_field'] ? $this->element['value_field'] : $this->name); $model = VmModel::getModel('Manufacturer'); $manufacturers = $model->getManufacturers(true, true, false); return JHTML::_('select.genericlist', $manufacturers, $this->name, 'class="inputbox" size="1"', 'virtuemart_manufacturer_id', 'mf_name', $this->value, $this->id); } }fields/category.php000066600000003606151372127700010356 0ustar00element['key_field'] ? $this->element['key_field'] : 'value'); $val = ($this->element['value_field'] ? $this->element['value_field'] : $this->name); VmConfig::loadJLang('com_virtuemart'); $categorylist = ShopFunctions::categoryListTree(array($this->value)); $html = '"; return $html; } }fields/orderstatus.php000066600000003364151372127700011121 0ustar00element['key_field'] ? $this->element['key_field'] : 'value'); $val = ($this->element['value_field'] ? $this->element['value_field'] : $this->name); $model = VmModel::getModel ('Orderstatus'); $orderStatus = $model->getOrderStatusList (); foreach ($orderStatus as $orderState) { $orderState->order_status_name = JText::_ ($orderState->order_status_name); } return JHTML::_ ('select.genericlist', $orderStatus, $this->name, 'class="inputbox" multiple="true" size="1"', 'order_status_code', 'order_status_name', $this->value, $this->id); } }customfields.php000066600000155551151372127700010003 0ustar00setMainTable ('product_customfields'); } /** * Gets a single custom by virtuemart_customfield_id * * @param string $type * @param string $mime mime type of custom, use for exampel image * @return customobject */ function getCustomfield () { $this->data = $this->getTable ('product_customfields'); $this->data->load ($this->_id); return $this; } // ************************************************** // Custom FIELDS // function getProductCustomsChilds ($childs) { $data = array(); foreach ($childs as $child) { $query = 'SELECT C.* , field.* FROM `#__virtuemart_product_customfields` AS field LEFT JOIN `#__virtuemart_customs` AS C ON C.`virtuemart_custom_id` = field.`virtuemart_custom_id` WHERE `virtuemart_product_id` =' . (int)$child->virtuemart_product_id; $query .= ' and C.field_type = "C" '; $this->_db->setQuery ($query); $child->field = $this->_db->loadObject (); $customfield = new stdClass(); $customfield->custom_value = $child->virtuemart_product_id; $customfield->field_type = 'C'; $child->display = $this->displayProductCustomfieldFE ($child, $customfield); if ($child->field) { $data[] = $child; } } return $data; } public function getCustomParentTitle ($custom_parent_id) { $q = 'SELECT custom_title FROM `#__virtuemart_customs` WHERE virtuemart_custom_id =' . (int)$custom_parent_id; $this->_db->setQuery ($q); return $this->_db->loadResult (); } /** @return autorized Types of data **/ function getField_types () { return array('S' => 'COM_VIRTUEMART_CUSTOM_STRING', 'I' => 'COM_VIRTUEMART_CUSTOM_INT', 'P' => 'COM_VIRTUEMART_CUSTOM_PARENT', 'B' => 'COM_VIRTUEMART_CUSTOM_BOOL', 'D' => 'COM_VIRTUEMART_DATE', 'T' => 'COM_VIRTUEMART_TIME', 'M' => 'COM_VIRTUEMART_IMAGE', 'V' => 'COM_VIRTUEMART_CUSTOM_CART_VARIANT', 'A' => 'COM_VIRTUEMART_CHILD_GENERIC_VARIANT', 'X' => 'COM_VIRTUEMART_CUSTOM_EDITOR', 'Y' => 'COM_VIRTUEMART_CUSTOM_TEXTAREA', 'E' => 'COM_VIRTUEMART_CUSTOM_EXTENSION' ); // 'U'=>'COM_VIRTUEMART_CUSTOM_CART_USER_VARIANT', // 'C'=>'COM_VIRTUEMART_CUSTOM_PRODUCT_CHILD', // 'G'=>'COM_VIRTUEMART_CUSTOM_PRODUCT_CHILD_GROUP', // 'R'=>'COM_VIRTUEMART_RELATED_PRODUCT', // 'Z'=>'COM_VIRTUEMART_RELATED_CATEGORY', } static function setParameterableByFieldType(&$table,$type=0){ if($type===0) $type = $table->field_type; $varsToPush = self::getVarsToPush($type); if(!empty($varsToPush)){ $table->setParameterable('custom_param',$varsToPush,TRUE); } } static function bindParameterableByFieldType(&$table,$type=0){ if($type===0) $type = $table->field_type; $varsToPush = self::getVarsToPush($type); if(!empty($varsToPush)){ VmTable::bindParameterable($table,'custom_param',$varsToPush); } } static function getVarsToPush($type){ $varsToPush = 0; if($type=='A'){ $varsToPush = array( 'withParent' => array(0, 'int'), 'parentOrderable' => array(0, 'int') ); } return $varsToPush; } private $_hidden = array(); /** * Use this to adjust the hidden fields of the displaycustomHandler to your form * * @author Max Milbers * @param string $name for exampel view * @param string $value for exampel custom */ public function addHidden ($name, $value = '') { $this->_hidden[$name] = $value; } /** * Adds the hidden fields which are needed for the form in every case * * @author Max Milbers * OBSELTE ? */ private function addHiddenByType ($datas) { $this->addHidden ('virtuemart_custom_id', $datas->virtuemart_custom_id); $this->addHidden ('option', 'com_virtuemart'); } /** * Displays a possibility to select custom groups * * @author Max Milbers * @author Maik K�nnemann * @author Patrick Kohl */ public function displayCustomSelection () { $customslist = $this->getParentList (); if (isset($this->virtuemart_custom_id)) { $value = $this->virtuemart_custom_id; } else { $value = JRequest::getInt ('custom_parent_id', 0); } return VmHTML::row ('select', 'COM_VIRTUEMART_CUSTOM_PARENT', 'custom_parent_id', $customslist, $value); } /** * Retrieve a list of layouts from the default and chosen templates directory. * * We may use here the getCustoms function of the custom model or write something simular * * @author Max Milbers * @param name of the view * @return object List of flypage objects */ function getCustomsList ($publishedOnly = FALSE) { $vendorId = 1; // get custom parents $q = 'SELECT virtuemart_custom_id as value ,custom_title as text FROM `#__virtuemart_customs` where custom_parent_id=0 AND field_type <> "R" AND field_type <> "Z" '; if ($publishedOnly) { $q .= 'AND `published`=1'; } if ($ID = JRequest::getInt ('virtuemart_custom_id', 0)) { $q .= ' and `virtuemart_custom_id`!=' . (int)$ID; } //if (isset($this->virtuemart_custom_id)) $q.=' and virtuemart_custom_id !='.$this->virtuemart_custom_id; $this->_db->setQuery ($q); // $result = $this->_db->loadAssocList(); $result = $this->_db->loadObjectList (); $errMsg = $this->_db->getErrorMsg (); $errs = $this->_db->getErrors (); if (!empty($errMsg)) { $app = JFactory::getApplication (); $errNum = $this->_db->getErrorNum (); $app->enqueueMessage ('SQL-Error: ' . $errNum . ' ' . $errMsg); } if ($errs) { $app = JFactory::getApplication (); foreach ($errs as $err) { $app->enqueueMessage ($err); } } return $result; } /** * This displays a custom handler. * * @param string $html atttributes, Just for displaying the fullsized image */ public function displayCustomFields ($datas) { $identify = ''; // ':'.$this->virtuemart_custom_id; if (!class_exists ('VmHTML')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'html.php'); } if ($datas->field_type) { $this->addHidden ('field_type', $datas->field_type); } $this->addHiddenByType ($datas); //$html = '
'.$datas->custom_title.'
'; $html = ""; //$html = ' '; if (!class_exists ('Permissions')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); } if (!Permissions::getInstance ()->check ('admin')) { $readonly = 'readonly'; } else { $readonly = ''; } // only input when not set else display if ($datas->field_type) { $html .= VmHTML::row ('value', 'COM_VIRTUEMART_CUSTOM_FIELD_TYPE', $datas->field_types[$datas->field_type]); } else { $html .= VmHTML::row ('select', 'COM_VIRTUEMART_CUSTOM_FIELD_TYPE', 'field_type', $this->getOptions ($datas->field_types), $datas->field_type, VmHTML::validate ('R')); } $html .= VmHTML::row ('input', 'COM_VIRTUEMART_TITLE', 'custom_title', $datas->custom_title, VmHTML::validate ('S')); $html .= VmHTML::row ('booleanlist', 'COM_VIRTUEMART_SHOW_TITLE', 'show_title', $datas->show_title); $html .= VmHTML::row ('booleanlist', 'COM_VIRTUEMART_PUBLISHED', 'published', $datas->published); $html .= VmHTML::row ('select', 'COM_VIRTUEMART_CUSTOM_PARENT', 'custom_parent_id', $this->getParentList ($datas->virtuemart_custom_id), $datas->custom_parent_id, ''); $html .= VmHTML::row ('booleanlist', 'COM_VIRTUEMART_CUSTOM_IS_CART_ATTRIBUTE', 'is_cart_attribute', $datas->is_cart_attribute); $html .= VmHTML::row ('input', 'COM_VIRTUEMART_DESCRIPTION', 'custom_field_desc', $datas->custom_field_desc); // change input by type $html .= VmHTML::row ('input', 'COM_VIRTUEMART_DEFAULT', 'custom_value', $datas->custom_value); $html .= VmHTML::row ('input', 'COM_VIRTUEMART_CUSTOM_TIP', 'custom_tip', $datas->custom_tip); $html .= VmHTML::row ('input', 'COM_VIRTUEMART_CUSTOM_LAYOUT_POS', 'layout_pos', $datas->layout_pos); //$html .= VmHTML::row('booleanlist','COM_VIRTUEMART_CUSTOM_PARENT','custom_parent_id',$this->getCustomsList(), $datas->custom_parent_id,''); $html .= VmHTML::row ('booleanlist', 'COM_VIRTUEMART_CUSTOM_ADMIN_ONLY', 'admin_only', $datas->admin_only); $html .= VmHTML::row ('booleanlist', 'COM_VIRTUEMART_CUSTOM_IS_LIST', 'is_list', $datas->is_list); $html .= VmHTML::row ('booleanlist', 'COM_VIRTUEMART_CUSTOM_IS_HIDDEN', 'is_hidden', $datas->is_hidden); // $html .= '
'; removed $html .= VmHTML::inputHidden ($this->_hidden); return $html; } /** * child classes can add their own options and you can get them with this function * * @param array $optionsarray */ private function getOptions ($field_types) { $options = array(); foreach ($field_types as $optionName=> $langkey) { $options[] = JHTML::_ ('select.option', $optionName, vmText::_ ($langkey)); } return $options; } /** * Just for creating simpel rows * * @author Max Milbers * @param string $descr * @param string $name */ private function displayRow ($descr, $name, $readonly = '') { $html = ' ' . vmText::_ ($descr) . ' '; return $html; } /** * * Enter description here ... * * @param unknown_type $excludedId * @return unknown|multitype: */ function getParentList ($excludedId = 0) { $this->_db->setQuery (' SELECT virtuemart_custom_id as value,custom_title as text FROM `#__virtuemart_customs` WHERE `field_type` ="P" and virtuemart_custom_id!=' . $excludedId); if ($results = $this->_db->loadObjectList ()) { return $results; } else { return array(); } } /** * * Enter description here ... */ function getProductChildCustomRelation () { $this->_db->setQuery (' SELECT virtuemart_custom_id as value,custom_title as text FROM `#__virtuemart_customs` WHERE `field_type` ="C"'); if ($results = $this->_db->loadObjectList ()) { return $results; } else { return array(); } } /** * * Enter description here ... * * @param unknown_type $product_id * @return unknown */ function getProductChildCustom ($product_id) { $this->_db->setQuery (' SELECT `virtuemart_custom_id`,`custom_value` FROM `#__virtuemart_product_customfields` WHERE `virtuemart_product_id` =' . (int)$product_id); if ($childcustom = $this->_db->loadObject ()) { return $childcustom; } else { $childcustom->virtuemart_custom_id = 0; $childcustom->custom_value = ''; return $childcustom; } } /** * * Enter description here ... * * @param unknown_type $product_id * @return string|Ambigous */ function getProductParentRelation ($product_id) { $this->_db->setQuery (' SELECT `custom_value` FROM `#__virtuemart_product_customfields` WHERE `virtuemart_product_id` =' . (int)$product_id); if ($childcustom = $this->_db->loadResult ()) { return '(' . $childcustom . ')'; } else { return vmText::_ ('COM_VIRTUEMART_CUSTOM_NO_PARENT_RELATION'); } } /** * AUthor Kohl Patrick * Load all custom fields for a Single product * return custom fields value and definition */ public function getproductCustomslist ($virtuemart_product_id, $parent_id = NULL) { $query = 'SELECT C.`virtuemart_custom_id` , `custom_element`, `custom_jplugin_id`, `custom_params`, `custom_parent_id` , `admin_only` , `custom_title` , `show_title` , `custom_tip` , C.`custom_value` AS value, `custom_field_desc` , `field_type` , `is_list` , `is_cart_attribute` , `is_hidden` , C.`published` , field.`virtuemart_customfield_id` , field.`custom_value`,field.`custom_param`,field.`custom_price`,field.`ordering` FROM `#__virtuemart_customs` AS C LEFT JOIN `#__virtuemart_product_customfields` AS field ON C.`virtuemart_custom_id` = field.`virtuemart_custom_id` Where `virtuemart_product_id` =' . $virtuemart_product_id . ' order by field.`ordering` ASC'; $this->_db->setQuery ($query); $productCustoms = $this->_db->loadObjectList (); //if (!$productCustoms ) return array(); if (!$productCustoms) { return; } $row = 0; foreach ($productCustoms as $field) { if ($parent_id) { $field->custom_value = ""; $field->virtuemart_customfield_id = ""; $field->custom_param = NULL; $virtuemart_product_id = $parent_id; } if ($field->field_type == 'E') { JPluginHelper::importPlugin ('vmcustom'); $dispatcher = JDispatcher::getInstance (); $retValue = $dispatcher->trigger ('plgVmDeclarePluginParams', array('custom', $field->custom_element, $field->custom_jplugin_id, $field)); }else { VirtueMartModelCustomfields::bindParameterableByFieldType($field); } //vmdebug('fields',$field); $field->display = $this->displayProductCustomfieldBE ($field, $virtuemart_product_id, $row); //custom_param without S !!! $row++; } return $productCustoms; } /* Save and delete from database * all product custom_fields and xref @ var $table : the xref table(eg. product,category ...) @array $data : array of customfields @int $id : The concerned id (eg. product_id) */ public function storeProductCustomfields($table,$datas, $id) { //vmdebug('storeProductCustomfields',$datas); JRequest::checkToken() or jexit( 'Invalid Token, in store customfields'); //Sanitize id $id = (int)$id; //Table whitelist $tableWhiteList = array('product','category','manufacturer'); if(!in_array($table,$tableWhiteList)) return false; // Get old IDS $this->_db->setQuery( 'SELECT `virtuemart_customfield_id` FROM `#__virtuemart_'.$table.'_customfields` as `PC` WHERE `PC`.virtuemart_'.$table.'_id ='.$id ); $old_customfield_ids = $this->_db->loadResultArray(); if (isset ( $datas['custom_param'] )) $params = true ; else $params = false ; if (array_key_exists('field', $datas)) { //vmdebug('datas save',$datas); $customfieldIds = array(); foreach($datas['field'] as $key => $fields){ $fields['virtuemart_'.$table.'_id'] =$id; $tableCustomfields = $this->getTable($table.'_customfields'); $tableCustomfields->setPrimaryKey('virtuemart_product_id'); if (!empty($datas['custom_param'][$key]) and !isset($datas['clone']) ) { if (array_key_exists( $key,$datas['custom_param'])) { $fields['custom_param'] = json_encode($datas['custom_param'][$key]); } } VirtueMartModelCustomfields::setParameterableByFieldType($tableCustomfields,$fields['field_type']); if(!isset($datas['clone'])){ VirtueMartModelCustomfields::bindParameterableByFieldType($tableCustomfields,$fields['field_type']); } $tableCustomfields->bindChecknStore($fields); $errors = $tableCustomfields->getErrors(); foreach($errors as $error){ vmError($error); } $key = array_search($fields['virtuemart_customfield_id'], $old_customfield_ids ); if ($key !== false ) unset( $old_customfield_ids[ $key ] ); // vmdebug('datas clone',$old_customfield_ids,$fields); } } if ( count($old_customfield_ids) ) { // delete old unused Customfields $this->_db->setQuery( 'DELETE FROM `#__virtuemart_'.$table.'_customfields` WHERE `virtuemart_customfield_id` in ("'.implode('","', $old_customfield_ids ).'") '); $this->_db->query(); } JPluginHelper::importPlugin('vmcustom'); $dispatcher = JDispatcher::getInstance(); if (isset($datas['plugin_param']) and is_array($datas['plugin_param'])) { foreach ($datas['plugin_param'] as $key => $plugin_param ) { $dispatcher->trigger('plgVmOnStoreProduct', array($datas, $plugin_param )); } } } /** * Formatting admin display by roles * input Types for product only ! * $field->is_cart_attribute if can have a price */ public function displayProductCustomfieldBE ($field, $product_id, $row) { $field->custom_value = empty($field->custom_value) ? $field->value : $field->custom_value; if ($field->is_cart_attribute) { if(!class_exists('VirtueMartModelVendor')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'vendor.php'); if(!class_exists('VirtueMartModelCurrency')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'currency.php'); $vendor_model = VmModel::getModel('vendor'); $vendor_model->setId(1); $vendor = $vendor_model->getVendor(); $currency_model = VmModel::getModel('currency'); $vendor_currency = $currency_model->getCurrency($vendor->vendor_currency); $priceInput = ' '.$vendor_currency->currency_symbol.""; } else { $priceInput = ' '; } if ($field->is_list) { $options = array(); $values = explode (';', $field->value); foreach ($values as $key => $val) { $options[] = array('value' => $val, 'text' => $val); } $currentValue = $field->custom_value; return JHTML::_ ('select.genericlist', $options, 'field[' . $row . '][custom_value]', null, 'value', 'text', $currentValue) . '' . $priceInput; } else { switch ($field->field_type) { case 'A': //vmdebug('displayProductCustomfieldBE $field',$field); if(!isset($field->withParent)) $field->withParent = 0; if(!isset($field->parentOrderable)) $field->parentOrderable = 0; //vmdebug('displayProductCustomfieldFE',$field); if (!class_exists('VmHTML')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'html.php'); $html = vmText::_('COM_VIRTUEMART_CUSTOM_WP').VmHTML::checkbox('field[' . $row . '][withParent]',$field->withParent,1,0,'').'
'; $html .= vmText::_('COM_VIRTUEMART_CUSTOM_PO').VmHTML::checkbox('field[' . $row . '][parentOrderable]',$field->parentOrderable,1,0,''); $options = array(); // $options[] = array( 'value' => 'product_name' ,'text' =>vmText::_('COM_VIRTUEMART_PRODUCT_FORM_NAME')); Is anyway displayed there $options[] = array('value' => 'product_sku', 'text' => vmText::_ ('COM_VIRTUEMART_PRODUCT_SKU')); $options[] = array('value' => 'slug', 'text' => vmText::_ ('COM_VIRTUEMART_PRODUCT_ALIAS')); $options[] = array('value' => 'product_length', 'text' => vmText::_ ('COM_VIRTUEMART_PRODUCT_LENGTH')); $options[] = array('value' => 'product_width', 'text' => vmText::_ ('COM_VIRTUEMART_PRODUCT_WIDTH')); $options[] = array('value' => 'product_height', 'text' => vmText::_ ('COM_VIRTUEMART_PRODUCT_HEIGHT')); $options[] = array('value' => 'product_weight', 'text' => vmText::_ ('COM_VIRTUEMART_PRODUCT_WEIGHT')); $html .= JHTML::_ ('select.genericlist', $options, 'field[' . $row . '][custom_value]', '', 'value', 'text', $field->custom_value) . '' . $priceInput; return $html; // return 'Automatic Childvariant creation (later you can choose here attributes to show, now product name) '; break; // variants case 'V': return '' . $priceInput; break; /* * Stockable (group of) child variants * Special type setted by the plugin */ case 'G': return; break; /*Extended by plugin*/ case 'E': $html = ''; if (!class_exists ('vmCustomPlugin')) { require(JPATH_VM_PLUGINS . DS . 'vmcustomplugin.php'); } JPluginHelper::importPlugin ('vmcustom', $field->custom_element); $dispatcher = JDispatcher::getInstance (); $retValue = ''; $dispatcher->trigger ('plgVmOnProductEdit', array($field, $product_id, &$row, &$retValue)); return $html . $retValue . ''. $priceInput; break; case 'D': return vmJsApi::jDate ($field->custom_value, 'field[' . $row . '][custom_value]', 'field_' . $row . '_customvalue') .''. $priceInput; break; case 'T': //TODO Patrick return '' . $priceInput; break; /* string or integer */ case 'S': case 'I': return '' . $priceInput; break; //'X'=>'COM_VIRTUEMART_CUSTOM_EDITOR', case 'X': // Not sure why this block is needed to get it to work when editing the customfield (the subsequent block works fine when creating it, ie. in JS) $document=& JFactory::getDocument(); if (get_class($document) == 'JDocumentHTML') { $editor =& JFactory::getEditor(); return $editor->display('field['.$row.'][custom_value]',$field->custom_value, '550', '400', '60', '20', false).''; } return ' ' . $priceInput; //return ''.$priceInput; break; //'Y'=>'COM_VIRTUEMART_CUSTOM_TEXTAREA' case 'Y': return '' . $priceInput; //return ''.$priceInput; break; case 'editorta': jimport ('joomla.html.editor'); $editor = JFactory::getEditor (); //TODO This is wrong! $_return['fields'][$_fld->name]['formcode'] = $editor->display ($_prefix . $_fld->name, $_return['fields'][$_fld->name]['value'], 300, 150, $_fld->cols, $_fld->rows); break; /* bool */ case 'B': return JHTML::_ ('select.booleanlist', 'field[' . $row . '][custom_value]', 'class="inputbox"', $field->custom_value) . '' . $priceInput; break; /* parent */ case 'P': return $field->custom_value . ''; break; /* related category*/ case 'Z': if (!$field->custom_value) { return ''; } // special case it's category ID ! $q = 'SELECT * FROM `#__virtuemart_categories_' . VMLANG . '` JOIN `#__virtuemart_categories` AS p using (`virtuemart_category_id`) WHERE `virtuemart_category_id`= "' . (int)$field->custom_value . '" '; $this->_db->setQuery ($q); //echo $this->_db->_sql; if ($category = $this->_db->loadObject ()) { $q = 'SELECT `virtuemart_media_id` FROM `#__virtuemart_category_medias` WHERE `virtuemart_category_id`= "' . (int)$field->custom_value . '" '; $this->_db->setQuery ($q); $thumb = ''; if ($media_id = $this->_db->loadResult ()) { $thumb = $this->displayCustomMedia ($media_id,'category'); } $display = ''; $display .= JHTML::link (JRoute::_ ('index.php?option=com_virtuemart&view=category&task=edit&virtuemart_category_id=' . (int)$field->custom_value,FALSE), ''.$thumb.'' . $category->category_name, array('title' => $category->category_name)).''; return $display; } else { return 'no result'; } /* related product*/ case 'R': if (!$field->custom_value) { return ''; } $pModel = VmModel::getModel('product'); $related = $pModel->getProduct((int)$field->custom_value,FALSE,FALSE,FALSE,1,FALSE); $thumb =''; if (!empty($related->virtuemart_media_id[0])) { $thumb = $this->displayCustomMedia ($related->virtuemart_media_id[0]).' '; } else { $thumb = $this->displayCustomMedia (0).' '; } $display = ''; $display .= JHTML::link (juri::root().'index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=' . $related->virtuemart_product_id . '&virtuemart_category_id=' . $related->virtuemart_category_id, ''.$thumb.''. $related->product_name, array('title' => $related->product_name,'target'=>'blank')).''; return $display; break; /* image */ case 'M': if (empty($product)) { $vendorId = 1; } else { $vendorId = $product->virtuemart_vendor_id; } $q = 'SELECT `virtuemart_media_id` as value,`file_title` as text FROM `#__virtuemart_medias` WHERE `published`=1 AND (`virtuemart_vendor_id`= "' . $vendorId . '" OR `shared` = "1")'; $this->_db->setQuery ($q); $options = $this->_db->loadObjectList (); return JHTML::_ ('select.genericlist', $options, 'field[' . $row . '][custom_value]', '', 'value', 'text', $field->custom_value) . '' . $priceInput; break; /* Child product */ /* case 'C': if (empty($product)){ $virtuemart_product_id = JRequest::getInt('virtuemart_product_id', 0); } else { $virtuemart_product_id = $product->virtuemart_product_id; } $html = ''; $q='SELECT concat(`product_sku`,":",`product_name`) as text ,`virtuemart_product_id`,`product_in_stock` FROM `#__virtuemart_products` WHERE `published`=1 AND `virtuemart_product_id`= "'.$field->custom_value.'"'; //$db->setQuery(' SELECT virtuemart_product_id, product_name FROM `#__virtuemart_products` WHERE `product_parent_id` ='.(int)$product_id); $this->_db->setQuery($q); if ($child = $this->_db->loadObject()) { $html .= JHTML::link ( JRoute::_ ( 'index.php?option=com_virtuemart&view=product&task=edit&virtuemart_product_id='.$field->custom_value), $child->text.' ('.$field->custom_value.')', array ('title' => $child->text )); $html .= ' '.vmText::_('COM_VIRTUEMART_PRODUCT_FORM_IN_STOCK').':'.$child->product_in_stock ; $html .= '
'.$priceInput; return $html; // return ''; } else return vmText::_('COM_VIRTUEMART_CUSTOM_NO_CHILD_PRODUCT'); break;*/ } } } public function getProductCustomsField ($product) { $query = 'SELECT C.`virtuemart_custom_id` , `custom_element`, `custom_params`, `custom_parent_id` , `admin_only` , `custom_title` , `show_title` , `custom_tip` , C.`custom_value` AS value, `custom_field_desc` , `field_type` , `is_list` , `is_hidden`, `layout_pos`, C.`published` , field.`virtuemart_customfield_id` , field.`custom_value`, field.`custom_param`, field.`custom_price`, field.`ordering` FROM `#__virtuemart_customs` AS C LEFT JOIN `#__virtuemart_product_customfields` AS field ON C.`virtuemart_custom_id` = field.`virtuemart_custom_id` Where `virtuemart_product_id` =' . (int)$product->virtuemart_product_id . ' and `field_type` != "G" and `field_type` != "R" and `field_type` != "Z"'; $query .= ' and is_cart_attribute = 0 order by field.`ordering`,virtuemart_custom_id'; $this->_db->setQuery ($query); if ($productCustoms = $this->_db->loadObjectList ()) { $row = 0; if (!class_exists ('vmCustomPlugin')) { require(JPATH_VM_PLUGINS . DS . 'vmcustomplugin.php'); } foreach ($productCustoms as $field) { if ($field->field_type == "E") { $field->display = ''; JPluginHelper::importPlugin ('vmcustom'); $dispatcher = JDispatcher::getInstance (); $ret = $dispatcher->trigger ('plgVmOnDisplayProductFE', array($product, &$row, &$field)); } else { $field->display = $this->displayProductCustomfieldFE ($product, $field, $row); } $row++; } return $productCustoms; } else { return array(); } } public function getProductCustomsFieldRelatedCategories ($product) { $query = 'SELECT C.`virtuemart_custom_id` , `custom_parent_id` , `admin_only` , `custom_title` , `custom_tip` , C.`custom_value` AS value, `custom_field_desc` , `field_type` , `is_list` , `is_hidden` , C.`published` , field.`virtuemart_customfield_id` , field.`custom_value`, field.`custom_param`, field.`custom_price`, field.`ordering` FROM `#__virtuemart_customs` AS C LEFT JOIN `#__virtuemart_product_customfields` AS field ON C.`virtuemart_custom_id` = field.`virtuemart_custom_id` Where `virtuemart_product_id` =' . (int)$product->virtuemart_product_id . ' and `field_type` = "Z"'; $query .= ' and is_cart_attribute = 0 order by ordering'; $this->_db->setQuery ($query); if ($productCustoms = $this->_db->loadObjectList ()) { $row = 0; foreach ($productCustoms as & $field) { $field->display = $this->displayProductCustomfieldFE ($product, $field, $row); $row++; } return $productCustoms; } else { return array(); } } public function getProductCustomsFieldRelatedProducts ($product) { $query = 'SELECT C.`virtuemart_custom_id` , `custom_parent_id` , `admin_only` , `custom_title` , `custom_tip` , C.`custom_value` AS value, `custom_field_desc` , `field_type` , `is_list` , `is_hidden` , C.`published` , field.`virtuemart_customfield_id` , field.`custom_value`, field.`custom_param`, field.`custom_price`, field.`ordering` FROM `#__virtuemart_customs` AS C LEFT JOIN `#__virtuemart_product_customfields` AS field ON C.`virtuemart_custom_id` = field.`virtuemart_custom_id` Where `virtuemart_product_id` =' . (int)$product->virtuemart_product_id . ' and `field_type` = "R"'; $query .= ' and is_cart_attribute = 0 order by ordering'; $this->_db->setQuery ($query); if ($productCustoms = $this->_db->loadObjectList ()) { $row = 0; foreach ($productCustoms as & $field) { $field->display = $this->displayProductCustomfieldFE ($product, $field, $row); $row++; } return $productCustoms; } else { return array(); } } /** * Display for the cart * * @author Patrick Kohl * @param obj $product product object * @return html code */ public function getProductCustomsFieldCart ($product) { // group by virtuemart_custom_id $query = 'SELECT C.`virtuemart_custom_id`, `custom_title`, `show_title`, C.`custom_value`,`custom_field_desc` ,`custom_tip`,`field_type`,field.`virtuemart_customfield_id`,`is_hidden` FROM `#__virtuemart_customs` AS C LEFT JOIN `#__virtuemart_product_customfields` AS field ON C.`virtuemart_custom_id` = field.`virtuemart_custom_id` Where `virtuemart_product_id` =' . (int)$product->virtuemart_product_id . ' and `field_type` != "G" and `field_type` != "R" and `field_type` != "Z"'; $query .= ' and is_cart_attribute = 1 group by virtuemart_custom_id ORDER BY field.`ordering`'; $this->_db->setQuery ($query); $groups = $this->_db->loadObjectList (); $err = $this->_db->getErrorMsg(); if(!empty($err)){ vmWarn('getProductCustomsFieldCart '.$err); } else { if(empty($groups)) return array(); } if (!class_exists ('VmHTML')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'html.php'); } $row = 0; if (!class_exists ('CurrencyDisplay')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'); } $currency = CurrencyDisplay::getInstance (); if (!class_exists ('calculationHelper')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php'); } $calculator = calculationHelper::getInstance (); $calculator ->_product = $product; $calculator->_cats = $product->categories; $calculator->product_tax_id = isset($product->product_tax_id)? $product->product_tax_id:0; $calculator->product_discount_id = isset($product->product_discount_id)? $product->product_discount_id:0; $calculator->productCurrency = isset($product->product_currency)? $product->product_currency:$calculator->productCurrency; if (!class_exists ('vmCustomPlugin')) { require(JPATH_VM_PLUGINS . DS . 'vmcustomplugin.php'); } //$free = vmText::_ ('COM_VIRTUEMART_CART_PRICE_FREE'); // render select list foreach ($groups as $group) { // $query='SELECT field.`virtuemart_customfield_id` as value ,concat(field.`custom_value`," :bu ", field.`custom_price`) AS text $query = 'SELECT field.`virtuemart_product_id`, `custom_params`,`custom_element`, field.`virtuemart_custom_id`, field.`virtuemart_customfield_id`,field.`custom_value`, field.`custom_price`, field.`custom_param` FROM `#__virtuemart_customs` AS C LEFT JOIN `#__virtuemart_product_customfields` AS field ON C.`virtuemart_custom_id` = field.`virtuemart_custom_id` Where `virtuemart_product_id` =' . (int)$product->virtuemart_product_id; $query .= ' and is_cart_attribute = 1 and C.`virtuemart_custom_id`=' . (int)$group->virtuemart_custom_id; // We want the field to be ordered as the user defined $query .= ' ORDER BY field.`ordering`'; $this->_db->setQuery ($query); $options = $this->_db->loadObjectList (); //vmdebug('getProductCustomsFieldCart options',$options); $group->options = array(); foreach ($options as $option) { $group->options[$option->virtuemart_customfield_id] = $option; } if ($group->field_type == 'V') { $default = current ($group->options); foreach ($group->options as $productCustom) { $price = self::_getCustomPrice($productCustom->custom_price, $currency, $calculator); $productCustom->text = vmText::_($productCustom->custom_value) . ' ' . $price; } $group->display = VmHTML::select ('customPrice[' . $row . '][' . $group->virtuemart_custom_id . ']', $group->options, $default->custom_value, '', 'virtuemart_customfield_id', 'text', FALSE, false); } else { if ($group->field_type == 'G') { $group->display .= ''; // no direct display done by plugin; } else { if ($group->field_type == 'E') { $group->display = ''; foreach ($group->options as $k=> $productCustom) { $price = self::_getCustomPrice($productCustom->custom_price, $currency, $calculator); $productCustom->text = $productCustom->custom_value . ' ' . $price; $productCustom->virtuemart_customfield_id = $k; if (!class_exists ('vmCustomPlugin')) { require(JPATH_VM_PLUGINS . DS . 'vmcustomplugin.php'); } //legacy, it will be removed 2.2 $productCustom->value = $productCustom->virtuemart_customfield_id; JPluginHelper::importPlugin ('vmcustom'); JPluginHelper::importPlugin ('vmcalculation'); $dispatcher = JDispatcher::getInstance (); $fieldsToShow = $dispatcher->trigger ('plgVmOnDisplayProductVariantFE', array($productCustom, &$row, &$group)); // $group->display .= ' '; $group->display .= ' '; if (!empty($currency->_priceConfig['variantModification'][0]) and $price !== '') { $group->display .= '
' . vmText::_ ('COM_VIRTUEMART_CART_PRICE') . '' . $price . '
'; } $row++; } $row--; } else { if ($group->field_type == 'U') { foreach ($group->options as $productCustom) { $price = self::_getCustomPrice($productCustom->custom_price, $currency, $calculator); $productCustom->text = $productCustom->custom_value . ' ' . $price; $group->display .= ' '; if (!empty($currency->_priceConfig['variantModification'][0]) and $price !== '') { $group->display .= '
' . vmText::_ ('COM_VIRTUEMART_CART_PRICE') . '' . $price . '
'; } } } else { if ($group->field_type == 'A') { $group->display = ''; foreach ($group->options as $productCustom) { /* if ((float)$productCustom->custom_price) { $price = $currency->priceDisplay ($calculator->calculateCustomPriceWithTax ($productCustom->custom_price)); } else { $price = ($productCustom->custom_price === '') ? '' : $free; }*/ $productCustom->field_type = $group->field_type; $productCustom->is_cart = 1; $group->display .= $this->displayProductCustomfieldFE ($product, $productCustom, $row); $checked = ''; } } else { $group->display = ''; $checked = 'checked="checked"'; foreach ($group->options as $productCustom) { //vmdebug('getProductCustomsFieldCart',$productCustom); $price = self::_getCustomPrice($productCustom->custom_price, $currency, $calculator); $productCustom->field_type = $group->field_type; $productCustom->is_cart = 1; // $group->display .= ''; //MarkerVarMods $group->display .= ''; $checked = ''; } } } } } } $row++; } return $groups; } static function _getCustomPrice($customPrice, $currency, $calculator) { if ((float)$customPrice) { $price = strip_tags ($currency->priceDisplay ($calculator->calculateCustomPriceWithTax ($customPrice))); if ($customPrice >0) { $price ="+".$price; } } else { $price = ($customPrice === '') ? '' : vmText::_ ('COM_VIRTUEMART_CART_PRICE_FREE'); } return $price; } /** * Formating front display by roles * for product only ! */ public function displayProductCustomfieldFE (&$product, $customfield, $row = '') { $virtuemart_custom_id = isset($customfield->virtuemart_custom_id)? $customfield->virtuemart_custom_id:0; $value = $customfield->custom_value; $type = $customfield->field_type; $is_list = isset($customfield->is_list)? $customfield->is_list:0; $price = isset($customfield->custom_price)? $customfield->custom_price:0; $is_cart = isset($customfield->is_cart)? $customfield->is_cart:0; //vmdebug('displayProductCustomfieldFE and here is something wrong ',$customfield); if (!class_exists ('CurrencyDisplay')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'); $currency = CurrencyDisplay::getInstance (); if ($is_list > 0) { $values = explode (';', $value); if ($is_cart != 0) { $options = array(); foreach ($values as $key => $val) { $options[] = array('value' => $val, 'text' => $val); } vmJsApi::chosenDropDowns(); return JHTML::_ ('select.genericlist', $options, 'field[' . $row . '][custom_value]', NULL, 'value', 'text', FALSE, TRUE); } else { $html = ''; $html .= '
' . $value . '
'; return $html; } } else { if ($price > 0) { $price = $currency->priceDisplay ((float)$price); } switch ($type) { case 'A': $options = array(); $session = JFactory::getSession (); $virtuemart_category_id = $session->get ('vmlastvisitedcategoryid', 0, 'vm'); $productModel = VmModel::getModel ('product'); //Note by Jeremy Magne (Daycounts) 2013-08-31 //Previously the the product model is loaded but we need to ensure the correct product id is set because the getUncategorizedChildren does not get the product id as parameter. //In case the product model was previously loaded, by a related product for example, this would generate wrong uncategorized children list $productModel->setId($product->virtuemart_product_id); //parseCustomParams VirtueMartModelCustomfields::bindParameterableByFieldType($customfield); //Todo preselection as dropdown of children //Note by Max Milbers: This is not necessary, in this case it is better to unpublish the parent and to give the child which should be preselected a category //Or it is withParent, in that case there exists the case, that a parent should be used as a kind of mini category and not be orderable. //There exists already other customs and in special plugins which wanna disable or change the add to cart button. //I suggest that we manipulate the button with a message "choose a variant first" //if(!isset($customfield->pre_selected)) $customfield->pre_selected = 0; $selected = JRequest::getVar ('virtuemart_product_id',0); if(is_array($selected) ) { $selected = $selected[0]; } $selected = (int) $selected; $html = ''; $uncatChildren = $productModel->getUncategorizedChildren ($customfield->withParent); if(empty($uncatChildren)){ return $html; break; } foreach ($uncatChildren as $child) { $options[] = array('value' => JRoute::_ ('index.php?option=com_virtuemart&view=productdetails&virtuemart_category_id=' . $virtuemart_category_id . '&virtuemart_product_id=' . $child['virtuemart_product_id'],FALSE), 'text' => $child['product_name']); } //vmJsApi::chosenDropDowns(); would need class="inputbox vm-chzn-select", but it does not work, in case people have two times the same product, //because both dropdowns have then the same id and the js does not work. $html .= JHTML::_ ('select.genericlist', $options, 'field[' . $row . '][custom_value]', 'onchange="window.top.location.href=this.options[this.selectedIndex].value" size="1" class="inputbox"', "value", "text", JRoute::_ ('index.php?option=com_virtuemart&view=productdetails&virtuemart_category_id=' . $virtuemart_category_id . '&virtuemart_product_id=' . $selected,FALSE)); //vmdebug('$customfield',$customfield); if($customfield->parentOrderable==0 and $product->product_parent_id==0){ $product->orderable = FALSE; } return $html; break; /* variants*/ case 'V': if ($price == 0) $price = vmText::_ ('COM_VIRTUEMART_CART_PRICE_FREE'); /* Loads the product price details */ return ' ' . vmText::_ ('COM_VIRTUEMART_CART_PRICE') . $price . ' '; break; /*Date variant*/ case 'D': return '' . vmJsApi::date ($value, 'LC1', TRUE) . ''; //vmJsApi::jDate($field->custom_value, 'field['.$row.'][custom_value]','field_'.$row.'_customvalue').$priceInput; break; /* text area or editor No vmText, only displayed in BE */ case 'X': case 'Y': return $value; break; /* string or integer */ case 'S': case 'I': return vmText::_ ($value); break; /* bool */ case 'B': if ($value == 0) return vmText::_ ('COM_VIRTUEMART_NO'); return vmText::_ ('COM_VIRTUEMART_YES'); break; /* parent */ case 'P': return '' . vmText::_ ($value) . ''; break; /* related */ case 'R': $pModel = VmModel::getModel('product'); $related = $pModel->getProduct((int)$value,TRUE,TRUE,TRUE,1,FALSE); if(!$related){ vmError('related product is missing, maybe unpublished '.$product->product_name.' id: '.$product->virtuemart_product_id); return false; } $thumb =''; if (!empty($related->virtuemart_media_id[0])) { $thumb = $this->displayCustomMedia ($related->virtuemart_media_id[0]).' '; } else { $thumb = $this->displayCustomMedia (0).' '; } return JHTML::link (JRoute::_ ('index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id=' . $related->virtuemart_product_id . '&virtuemart_category_id=' . $related->virtuemart_category_id,FALSE), $thumb . $related->product_name, array('title' => $related->product_name)); break; /* image */ case 'M': return $this->displayCustomMedia ($value); break; /* categorie */ case 'Z': $q = 'SELECT * FROM `#__virtuemart_categories_' . VMLANG . '` as l JOIN `#__virtuemart_categories` AS c using (`virtuemart_category_id`) WHERE `published`=1 AND l.`virtuemart_category_id`= "' . (int)$value . '" '; $this->_db->setQuery ($q); if ($category = $this->_db->loadObject ()) { $q = 'SELECT `virtuemart_media_id` FROM `#__virtuemart_category_medias`WHERE `virtuemart_category_id`= "' . $category->virtuemart_category_id . '" '; $this->_db->setQuery ($q); $thumb = ''; if ($media_id = $this->_db->loadResult ()) { $thumb = $this->displayCustomMedia ($media_id,'category'); } return JHTML::link (JRoute::_ ('index.php?option=com_virtuemart&view=category&virtuemart_category_id=' . $category->virtuemart_category_id, FALSE), $thumb . ' ' . $category->category_name, array('title' => $category->category_name)); } else return ''; /* Child Group list * this have no direct display , used for stockable product */ case 'G': return ''; //' '.vmText::_('COM_VIRTUEMART_CART_PRICE').' : '.$price .' '; break; break; } } } function displayCustomMedia ($media_id, $table = 'product', $absUrl = FALSE) { if (!class_exists ('TableMedias')) require(JPATH_VM_ADMINISTRATOR . DS . 'tables' . DS . 'medias.php'); //$data = $this->getTable('medias'); $db = JFactory::getDBO (); $data = new TableMedias($db); $data->load ((int)$media_id); if (!class_exists ('VmMediaHandler')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'mediahandler.php'); $media = VmMediaHandler::createMedia ($data, $table); //if($media_id==0){ // return $media->getIcon('', FALSE, TRUE, TRUE,$absUrl); //} return $media->displayMediaThumb ('', FALSE, '', TRUE, TRUE, $absUrl); } /** * There are too many functions doing almost the same for my taste * the results are sometimes slighty different and makes it hard to work with it, therefore here the function for future proxy use * */ public static function customFieldDisplay ($product, $variantmods, $html, $trigger) { //vmdebug('customFieldDisplay $variantmods',$variantmods); $row = 0; if (!class_exists ('shopFunctionsF')) require(JPATH_VM_SITE . DS . 'helpers' . DS . 'shopfunctionsf.php'); //MarkerVarMods foreach ($variantmods as $selected => $variant) { //foreach ($variantmods as $variant=> $selected) { //vmdebug('customFieldDisplay '.$variant.' '.$selected); if ($selected) { $productCustom = self::getProductCustomField ($selected); //vmdebug('customFieldDisplay',$selected,$productCustom); if (!empty($productCustom)) { $html .= ''; if ($productCustom->field_type == "E") { $product = self::addParam ($product); $product->productCustom = $productCustom; //vmdebug('CustomsFieldCartDisplay $productCustom',$productCustom); // vmdebug('customFieldDisplay $product->param selected '.$selected,$product->param); if (!class_exists ('vmCustomPlugin')) require(JPATH_VM_PLUGINS . DS . 'vmcustomplugin.php'); JPluginHelper::importPlugin ('vmcustom'); $dispatcher = JDispatcher::getInstance (); $dispatcher->trigger ($trigger, array($product, $row, &$html)); } else { //vmdebug('customFieldDisplay $productCustom by self::getProductCustomField $variant: '.$variant.' $selected: '.$selected,$productCustom); $value = ''; if (($productCustom->field_type == "G")) { $child = self::getChild ($productCustom->custom_value); // $html .= $productCustom->custom_title.' '.$child->product_name; $value = $child->product_name; } elseif (($productCustom->field_type == "M")) { // $html .= $productCustom->custom_title.' '.self::displayCustomMedia($productCustom->custom_value); $value = self::displayCustomMedia ($productCustom->custom_value); } elseif (($productCustom->field_type == "S")) { // q $html .= $productCustom->custom_title.' '.vmText::_($productCustom->custom_value); $value = $productCustom->custom_value; } else { // $html .= $productCustom->custom_title.' '.$productCustom->custom_value; //vmdebug('customFieldDisplay',$productCustom); $value = $productCustom->custom_value; } $html .= ShopFunctionsF::translateTwoLangKeys ($productCustom->show_title ? $productCustom->custom_title : '', $value); } $html .= '
'; } else { // falldown method if customfield are deleted foreach ((array)$selected as $key => $value) { $html .= '
Couldnt find customfield' . ($key ? '' . $key . ' ' : '') . $value; } } } $row++; } // vmdebug ('customFieldDisplay html begin: ' . $html . ' end'); return $html . '
'; } /** * TODO This is html and view stuff and MUST NOT be in the model, notice by Max * render custom fields display cart module FE */ public static function CustomsFieldCartModDisplay ($priceKey, $product) { if (empty($calculator)) { if (!class_exists ('calculationHelper')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php'); $calculator = calculationHelper::getInstance (); } $variantmods = $calculator->parseModifier ($priceKey); return self::customFieldDisplay ($product, $variantmods, '
', 'plgVmOnViewCartModule'); } /** * TODO This is html and view stuff and MUST NOT be in the model, notice by Max * render custom fields display cart FE */ public static function CustomsFieldCartDisplay ($priceKey, $product) { if (empty($calculator)) { if (!class_exists ('calculationHelper')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php'); $calculator = calculationHelper::getInstance (); } $variantmods = $calculator->parseModifier ($priceKey); return self::customFieldDisplay ($product, $variantmods, '
', 'plgVmOnViewCart'); } /* * render custom fields display order BE/FE */ public function CustomsFieldOrderDisplay ($item, $view = 'FE', $absUrl = FALSE) { $row = 0; // $item=(array)$item; if (!empty($item->product_attribute)) { $item->param = json_decode ($item->product_attribute, TRUE); // $html = '
'; if (!empty($item->param)) { return self::customFieldDisplay ($item, $item->param, '
', 'plgVmDisplayInOrder' . $view); } else { vmdebug ('CustomsFieldOrderDisplay $item->param empty? '); } } else { // vmTrace('$item->product_attribut is empty'); } return FALSE; } /** * * custom fields for cart and cart module */ public static function getProductCustomField ($selected) { $db = JFactory::getDBO (); $query = 'SELECT C.`virtuemart_custom_id` , `custom_element` , `custom_parent_id` , `admin_only` , `custom_title` , `show_title` , `custom_tip` , C.`custom_value` AS value, `custom_field_desc` , `field_type` , `is_list` , `is_cart_attribute` , `is_hidden` , C.`published` , field.`virtuemart_customfield_id` , field.`custom_value`,field.`custom_param`,field.`custom_price` FROM `#__virtuemart_customs` AS C LEFT JOIN `#__virtuemart_product_customfields` AS field ON C.`virtuemart_custom_id` = field.`virtuemart_custom_id` WHERE `virtuemart_customfield_id` ="' . (int)$selected . '"'; // if($product_parent_id!=0){ // $query .= ' AND (`virtuemart_product_id` ="' . $product_id.'" XOR `virtuemart_product_id` ="' . $product_parent_id.'")'; // } else { // $query .= ' AND (`virtuemart_product_id` ="' . $product_id.'"'; // } $db->setQuery ($query); return $db->loadObject (); } /* * add parameter to product definition */ public function addParam ($product) { // vmdebug('addParam? ',$product->custom_param,$product->customPlugin); $custom_param = empty($product->custom_param) ? array() : json_decode ($product->custom_param, TRUE); $product_param = empty($product->customPlugin) ? array() : json_decode ($product->customPlugin, TRUE); $params = (array)$product_param + (array)$custom_param; foreach ($params as $key => $param) { $product->param[$key] = $param; } return $product; } public function getChild ($child) { $db = JFactory::getDBO (); $db->setQuery ('SELECT `product_sku`, `product_name` FROM `#__virtuemart_products_' . VMLANG . '` WHERE virtuemart_product_id=' . $child); return $db->loadObject (); } static public function setEditCustomHidden ($customfield, $i) { if (!isset($customfield->virtuemart_customfield_id)) $customfield->virtuemart_customfield_id = '0'; $html = ' '; return $html; } } // pure php no closing tag user.php000066600000141265151372127700006255 0ustar00setMainTable('vmusers'); $this->setToggleName('user_is_vendor'); $this->addvalidOrderingFieldName(array('ju.username','ju.name','sg.virtuemart_shoppergroup_id','shopper_group_name','shopper_group_desc') ); array_unshift($this->_validOrderingFieldName,'ju.id'); // $user = JFactory::getUser(); // $this->_id = $user->id; } /** * public function Resets the user id and data * * * @author Max Milbers */ public function setId($cid){ $user = JFactory::getUser(); //anonymous sets to 0 for a new entry if(empty($user->id)){ $userId = 0; //echo($this->_id,'Recognized anonymous case'); } else { //not anonymous, but no cid means already registered user edit own data if(empty($cid)){ $userId = $user->id; // vmdebug('setId setCurrent $user',$user->get('id')); } else { if($cid != $user->id){ if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(Permissions::getInstance()->check("admin")) { $userId = $cid; // vmdebug('Admin watches user, setId '.$cid); } else { JError::raiseWarning(1,'Hacking attempt'); $userId = $user->id; } }else { $userId = $user->id; } } } $this->setUserId($userId); return $userId; } /** * Internal function * * @param unknown_type $id */ private function setUserId($id){ $app = JFactory::getApplication(); // if($app->isAdmin()){ if($this->_id!=$id){ $this->_id = (int)$id; $this->_data = null; $this->customer_number = 0; } // } } public function getCurrentUser(){ $user = JFactory::getUser(); $this->setUserId($user->id); return $this->getUser(); } private $_defaultShopperGroup = 0; /** * Sets the internal user id with given vendor Id * * @author Max Milbers * @param int $vendorId */ function getVendor($vendorId=1,$return=TRUE){ $vendorModel = VmModel::getModel('vendor'); $userId = VirtueMartModelVendor::getUserIdByVendorId($vendorId); if($userId){ $this->setUserId($userId); if($return){ return $this->getUser(); } } else { return false; } } /** * Retrieve the detail record for the current $id if the data has not already been loaded. * @author Max Milbers */ function getUser(){ if(!empty($this->_data)) return $this->_data; if(empty($this->_db)) $this->_db = JFactory::getDBO(); $this->_data = $this->getTable('vmusers'); $this->_data->load((int)$this->_id); // vmdebug('$this->_data->vmusers',$this->_data); $this->_data->JUser = JUser::getInstance($this->_id); // vmdebug('$this->_data->JUser',$this->_data->JUser); if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); $this->_data->perms = Permissions::getInstance()->getPermissions((int)$this->_id); // Add the virtuemart_shoppergroup_ids $xrefTable = $this->getTable('vmuser_shoppergroups'); $this->_data->shopper_groups = $xrefTable->load($this->_id); $shoppergroupmodel = VmModel::getModel('ShopperGroup'); $site = JFactory::getApplication ()->isSite (); if($site){ if(empty($this->_data->shopper_groups)) $this->_data->shopper_groups = array(); $shoppergroupmodel->appendShopperGroups($this->_data->shopper_groups,$this->_data->JUser,$site); } if(!empty($this->_id)) { $q = 'SELECT `virtuemart_userinfo_id` FROM `#__virtuemart_userinfos` WHERE `virtuemart_user_id` = "' . (int)$this->_id.'"'; $this->_db->setQuery($q); $userInfo_ids = $this->_db->loadResultArray(0); } else { $userInfo_ids = array(); } // vmdebug('my query',$this->_db->getQuery()); //vmdebug('my $_ui',$userInfo_ids,$this->_id); $this->_data->userInfo = array (); $BTuid = 0; foreach($userInfo_ids as $uid){ $this->_data->userInfo[$uid] = $this->getTable('userinfos'); $this->_data->userInfo[$uid]->load($uid); if ($this->_data->userInfo[$uid]->address_type == 'BT') { $BTuid = $uid; $this->_data->userInfo[$BTuid]->name = $this->_data->JUser->name; $this->_data->userInfo[$BTuid]->email = $this->_data->JUser->email; $this->_data->userInfo[$BTuid]->username = $this->_data->JUser->username; $this->_data->userInfo[$BTuid]->address_type = 'BT'; // vmdebug('$this->_data->vmusers',$this->_data); } } // vmdebug('user_is_vendor ?',$this->_data->user_is_vendor); if($this->_data->user_is_vendor){ $vendorModel = VmModel::getModel('vendor'); if(Vmconfig::get('multix','none')=='none'){ $this->_data->virtuemart_vendor_id = 1; //vmdebug('user model, single vendor',$this->_data->virtuemart_vendor_id); } $vendorModel->setId($this->_data->virtuemart_vendor_id); $this->_data->vendor = $vendorModel->getVendor(); } return $this->_data; } /** * Retrieve contact info for a user if any * * @return array of null */ function getContactDetails() { if ($this->_id) { $this->_db->setQuery('SELECT * FROM #__contact_details WHERE user_id = ' . $this->_id); $_contacts = $this->_db->loadObjectList(); if (count($_contacts) > 0) { return $_contacts[0]; } } return null; } /** * Functions belonging to get_groups_below_me Taken with correspondence from CommunityBuilder * adjusted to the our needs * @version $Id: user.php 6543 2012-10-16 06:41:27Z Milbo $ * @package Community Builder * @subpackage cb.acl.php * @author Beat and mambojoe * @author Max Milbers * @copyright (C) Beat, www.joomlapolis.com * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2 */ function get_object_id( $var_1 = null, $var_2 = null, $var_3 = null ) { if ( JVM_VERSION === 2) { $return = $var_2; } else { $return = $this->_acl->get_object_id( $var_1, $var_2, $var_3 ); } return $return; } /** * Taken with correspondence from CommunityBuilder * adjusted to the our needs * @version $Id: user.php 6543 2012-10-16 06:41:27Z Milbo $ * @package Community Builder * @subpackage cb.acl.php * @author Beat and mambojoe * @author Max Milbers * @copyright (C) Beat, www.joomlapolis.com * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2 */ function get_object_groups( $var_1 = null, $var_2 = null, $var_3 = null ) { if ( version_compare(JVERSION,'1.6.0','ge') ) { $user_id = ( is_integer( $var_1 ) ? $var_1 : $var_2 ); $recurse = ( $var_3 == 'RECURSE' ? true : false ); $return = $this->_acl->getGroupsByUser( $user_id, $recurse ); } else { if ( ! $var_2 ) { $var_2 = 'ARO'; } if ( ! $var_3 ) { $var_3 = 'NO_RECURSE'; } $return = $this->_acl->get_object_groups( $var_1, $var_2, $var_3 ); } return $return; } /** * Remap literal groups (such as in default values) to the hardcoded CMS values * * @param string|array $name of int|string * @return int|array of int */ function mapGroupNamesToValues( $name ) { static $ps = null; $selected = (array) $name; foreach ( $selected as $k => $v ) { if ( ! is_numeric( $v ) ) { if ( ! $ps ) { if ( JVM_VERSION === 2 ) { $ps = array( 'Root' => 0 , 'Users' => 0 , 'Public' => 1, 'Registered' => 2, 'Author' => 3, 'Editor' => 4, 'Publisher' => 5, 'Backend' => 0 , 'Manager' => 6, 'Administrator' => 7, 'Superadministrator' => 8 ); } else { $ps = array( 'Root' => 17, 'Users' => 28, 'Public' => 29, 'Registered' => 18, 'Author' => 19, 'Editor' => 20, 'Publisher' => 21, 'Backend' => 30, 'Manager' => 23, 'Administrator' => 24, 'Superadministrator' => 25 ); } } if ( array_key_exists( $v, $ps ) ) { if ( $ps[$v] != 0 ) { $selected[$k] = $ps[$v]; } else { unset( $selected[$k] ); } } else { $selected[$k] = (int) $v; } } } if ( ! is_array( $name ) ) { $selected = $selected[0]; } return $selected; } function get_group_children_tree( $var_1 = null, $var_2 = null, $var_3 = null, $var_4 = null ) { $_CB_database = &$this->getDbo(); if ( ! $var_4 ) { $var_4 = true; } if ( JVM_VERSION === 2 ) { $query = 'SELECT a.' . $_CB_database->NameQuote( 'id' ) . ' AS value' . ', a.' . $_CB_database->NameQuote( 'title' ) . ' AS text' . ', COUNT( DISTINCT b.' . $_CB_database->NameQuote( 'id' ) . ' ) AS level' . "\n FROM " . $_CB_database->NameQuote( '#__usergroups' ) . " AS a" . "\n LEFT JOIN " . $_CB_database->NameQuote( '#__usergroups' ) . " AS b" . ' ON a.' . $_CB_database->NameQuote( 'lft' ) . ' > b.' . $_CB_database->NameQuote( 'lft' ) . ' AND a.' . $_CB_database->NameQuote( 'rgt' ) . ' < b.' . $_CB_database->NameQuote( 'rgt' ) . "\n GROUP BY a." . $_CB_database->NameQuote( 'id' ) . "\n ORDER BY a." . $_CB_database->NameQuote( 'lft' ) . " ASC"; $_CB_database->setQuery( $query ); $groups = $_CB_database->loadObjectList(); $user_groups = array(); for ( $i = 0, $n = count( $groups ); $i < $n; $i++ ) { $groups[$i]->text = str_repeat( '- ', $groups[$i]->level ) . JText::_( $groups[$i]->text ); if ( $var_4 ) { $user_groups[$i] = JHtml::_( 'select.option', $groups[$i]->value, $groups[$i]->text ); } else { $user_groups[$i] = array( 'value' => $groups[$i]->value, 'text' => $groups[$i]->text ); } } $return = $user_groups; } else { if ( ! $var_3 ) { $var_3 = true; } $return = $this->_acl->get_group_children_tree( $var_1, $var_2, $var_3, $var_4 ); } return $return; } /** * Return a list with groups that can be set by the current user * * @return mixed Array with groups that can be set, or the groupname (string) if it cannot be changed. */ function getGroupList() { if(JVM_VERSION === 2) { //hm CB thing also not help // $_grpList = $this->get_groups_below_me(); // return $_grpList; /* if(!class_exists('UsersModelUser')) require(JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_users'.DS.'models'.DS.'user.php'); $jUserModel = new UsersModelUser(); $list = $jUserModel->getGroups(); $user = JFactory::getUser(); if ($user->authorise('core.edit', 'com_users') && $user->authorise('core.manage', 'com_users')) { $model = JModel::getInstance('Groups', 'UsersModel', array('ignore_request' => true)); return $model->getItems(); } else { return null; }*/ $user = JFactory::getUser(); $authGroups = JAccess::getGroupsByUser($user->id); // $authGroups = $user->getAuthorisedGroups(); // vmdebug('getGroupList j17',$authGroups); $db = $this->getDbo(); $where = implode($authGroups,'" OR `id` = "').'"'; $q = 'SELECT `id` as value,`title` as text FROM #__usergroups WHERE `id` = "'.$where; $db->setQuery($q); $list = $db->loadAssocList(); // foreach($list as $item){ // vmdebug('getGroupList $item ',$item); // } // vmdebug('getGroupList $q '.$list); return $list; } else { $_aclObject = JFactory::getACL(); if(empty($this->_data)) $this->getUser(); if (JVM_VERSION>1){ //TODO fix this latter. It's just an workarround to make it working on 1.6 $gids = $this->_data->JUser->get('groups'); return array_flip($gids); } $_usr = $_aclObject->get_object_id ('users', $this->_data->JUser->get('id'), 'ARO'); $_grp = $_aclObject->get_object_groups ($_usr, 'ARO'); $_grpName = strtolower ($_aclObject->get_group_name($_grp[0], 'ARO')); $_currentUser = JFactory::getUser(); $_my_usr = $_aclObject->get_object_id ('users', $_currentUser->get('id'), 'ARO'); $_my_grp = $_aclObject->get_object_groups ($_my_usr, 'ARO'); $_my_grpName = strtolower ($_aclObject->get_group_name($_my_grp[0], 'ARO')); // administrators can't change each other and frontend-only users can only see groupnames if (( $_grpName == $_my_grpName && $_my_grpName == 'administrator' ) || !$_aclObject->is_group_child_of($_my_grpName, 'Public Backend')) { return $_grpName; } else { $_grpList = $_aclObject->get_group_children_tree(null, 'USERS', false); $_remGroups = $_aclObject->get_group_children( $_my_grp[0], 'ARO', 'RECURSE' ); if (!$_remGroups) { $_remGroups = array(); } // Make sure privs higher than my own can't be granted if (in_array($_grp[0], $_remGroups)) { // nor can privs of users with higher privs be decreased. return $_grpName; } $_i = 0; $_j = count($_grpList); while ($_i < $_j) { if (in_array($_grpList[$_i]->value, $_remGroups)) { array_splice( $_grpList, $_i, 1 ); $_j = count($_grpList); } else { $_i++; } } return $_grpList; } } } /** * Bind the post data to the JUser object and the VM tables, then saves it * It is used to register new users * This function can also change already registered users, this is important when a registered user changes his email within the checkout. * * @author Max Milbers * @author Oscar van Eijk * @return boolean True is the save was successful, false otherwise. */ public function store(&$data,$checkToken = TRUE){ $message = ''; $user = ''; $newId = 0; if($checkToken){ JRequest::checkToken() or jexit( 'Invalid Token, while trying to save user' ); $mainframe = JFactory::getApplication() ; } if(empty($data)){ vmError('Developer notice, no data to store for user'); return false; } //To find out, if we have to register a new user, we take a look on the id of the usermodel object. //The constructor sets automatically the right id. $new = ($this->_id < 1); if(empty($this->_id)){ $user = new JUser(); //thealmega http://forum.virtuemart.net/index.php?topic=99755.msg393758#msg393758 } else { $user = JFactory::getUser($this->_id); } $gid = $user->get('gid'); // Save original gid // Preformat and control user datas by plugin JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $valid = true ; $dispatcher->trigger('plgVmOnBeforeUserfieldDataSave',array(&$valid,$this->_id,&$data,$user )); // $valid must be false if plugin detect an error if( $valid == false ) { return false; } // Before I used this "if($cart && !$new)" // This construction is necessary, because this function is used to register a new JUser, so we need all the JUser data in $data. // On the other hand this function is also used just for updating JUser data, like the email for the BT address. In this case the // name, username, password and so on is already stored in the JUser and dont need to be entered again. if(empty ($data['email'])){ $email = $user->get('email'); if(!empty($email)){ $data['email'] = $email; } } else { $data['email'] = JRequest::getString('email', '', 'post', 'email'); } $data['email'] = str_replace(array('\'','"',',','%','*','/','\\','?','^','`','{','}','|','~'),array(''),$data['email']); //This is important, when a user changes his email address from the cart, //that means using view user layout edit_address (which is called from the cart) $user->set('email',$data['email']); if(empty ($data['name'])){ $name = $user->get('name'); if(!empty($name)){ $data['name'] = $name; } } else { $data['name'] = JRequest::getString('name', '', 'post', 'name'); } $data['name'] = str_replace(array('\'','"',',','%','*','/','\\','?','^','`','{','}','|','~'),array(''),$data['name']); if(empty ($data['username'])){ $username = $user->get('username'); if(!empty($username)){ $data['username'] = $username; } else { $data['username'] = JRequest::getVar('username', '', 'post', 'username'); } } if(empty ($data['password'])){ $data['password'] = JRequest::getVar('password', '', 'post', 'string' ,JREQUEST_ALLOWRAW); } if(empty ($data['password2'])){ $data['password2'] = JRequest::getVar('password2', '', 'post', 'string' ,JREQUEST_ALLOWRAW); } if(!$new && !empty($data['password']) && empty($data['password2'])){ unset($data['password']); unset($data['password2']); } // Bind Joomla userdata if (!$user->bind($data)) { foreach($user->getErrors() as $error) { // vmError('user bind '.$error); vmError('user bind '.$error,JText::sprintf('COM_VIRTUEMART_USER_STORE_ERROR',$error)); } $message = 'Couldnt bind data to joomla user'; array('user'=>$user,'password'=>$data['password'],'message'=>$message,'newId'=>$newId,'success'=>false); } if($new){ // If user registration is not allowed, show 403 not authorized. // But it is possible for admins and storeadmins to save $usersConfig = JComponentHelper::getParams( 'com_users' ); if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if (!Permissions::getInstance()->check("admin,storeadmin") && $usersConfig->get('allowUserRegistration') == '0') { VmConfig::loadJLang('com_virtuemart'); JError::raiseError( 403, JText::_('COM_VIRTUEMART_ACCESS_FORBIDDEN')); return; } $authorize = JFactory::getACL(); // Initialize new usertype setting $newUsertype = $usersConfig->get( 'new_usertype' ); if (!$newUsertype) { if ( JVM_VERSION===1){ $newUsertype = 'Registered'; } else { $newUsertype = 2; } } // Set some initial user values $user->set('usertype', $newUsertype); if ( JVM_VERSION===1){ $user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' )); } else { $user->groups[] = $newUsertype; } $date = JFactory::getDate(); $user->set('registerDate', $date->toMySQL()); // If user activation is turned on, we need to set the activation information $useractivation = $usersConfig->get( 'useractivation' ); $doUserActivation=false; if ( JVM_VERSION===1){ if ($useractivation == '1' ) { $doUserActivation=true; } } else { if ($useractivation == '1' or $useractivation == '2') { $doUserActivation=true; } } vmdebug('user',$useractivation , $doUserActivation); if ($doUserActivation ) { jimport('joomla.user.helper'); $user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) ); $user->set('block', '1'); //$user->set('lastvisitDate', '0000-00-00 00:00:00'); } } $option = JRequest::getCmd( 'option'); // If an exising superadmin gets a new group, make sure enough admins are left... if (!$new && $user->get('gid') != $gid && $gid == __SUPER_ADMIN_GID) { if ($this->getSuperAdminCount() <= 1) { vmError(JText::_('COM_VIRTUEMART_USER_ERR_ONLYSUPERADMIN')); return false; } } if(isset($data['language'])){ $user->setParam('language',$data['language']); } // Save the JUser object if (!$user->save()) { vmError(JText::_( $user->getError()) , JText::_( $user->getError())); return false; } //vmdebug('my user, why logged in? ',$user); $newId = $user->get('id'); $data['virtuemart_user_id'] = $newId; //We need this in that case, because data is bound to table later $this->setUserId($newId); //Save the VM user stuff if(!$this->saveUserData($data) || !self::storeAddress($data)){ vmError('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USER_DATA'); // vmError(Jtext::_('COM_VIRTUEMART_NOT_ABLE_TO_SAVE_USERINFO_DATA')); } else { if ($new) { $this->sendRegistrationEmail($user,$user->password_clear, $doUserActivation); if ($doUserActivation ) { vmInfo('COM_VIRTUEMART_REG_COMPLETE_ACTIVATE'); } else { vmInfo('COM_VIRTUEMART_REG_COMPLETE'); $user->set('activation', '' ); $user->set('block', '0'); $user->set('guest', '0'); } } else { vmInfo('COM_VIRTUEMART_USER_DATA_STORED'); } } //The extra check for isset vendor_name prevents storing of the vendor if there is no form (edit address cart) if((int)$data['user_is_vendor']==1 and isset($data['vendor_name'])){ vmdebug('vendor recognised '.$data['virtuemart_vendor_id']); if($this ->storeVendorData($data)){ if ($new) { if ($doUserActivation ) { vmInfo('COM_VIRTUEMART_REG_VENDOR_COMPLETE_ACTIVATE'); } else { vmInfo('COM_VIRTUEMART_REG_VENDOR_COMPLETE'); } } else { vmInfo('COM_VIRTUEMART_VENDOR_DATA_STORED'); } } } return array('user'=>$user,'password'=>$data['password'],'message'=>$message,'newId'=>$newId,'success'=>true); } /** * This function is NOT for anonymous. Anonymous just get the information directly sent by email. * This function saves the vm Userdata for registered JUsers. * TODO, setting of shoppergroup isnt done * * TODO No reason not to use this function for new users, but it requires a Joomla plugin * that gets fired by the onAfterStoreUser. I'll built that (OvE) * * Notice: * As long we do not have the silent registration, an anonymous does not get registered. It is enough to send the virtuemart_order_id * with the email. The order is saved with all information in an extra table, so there is * no need for a silent registration. We may think about if we actually need/want the feature silent registration * The information of anonymous is stored in the order table and has nothing todo with the usermodel! * * @author Max Milbers * @author Oscar van Eijk * return boolean */ public function saveUserData(&$data,$trigger=true){ if(empty($this->_id)){ echo 'This is a notice for developers, you used this function for an anonymous user, but it is only designed for already registered ones'; vmError( 'This is a notice for developers, you used this function for an anonymous user, but it is only designed for already registered ones'); return false; } $noError = true; $usertable = $this->getTable('vmusers'); $alreadyStoredUserData = $usertable->load($this->_id); $app = JFactory::getApplication(); if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check("admin")){ unset($data['virtuemart_vendor_id']); unset($data['user_is_vendor']); $data['user_is_vendor'] = $alreadyStoredUserData->user_is_vendor; $data['virtuemart_vendor_id'] = $alreadyStoredUserData->virtuemart_vendor_id; } else { if(!isset($data['user_is_vendor']) and !empty($alreadyStoredUserData->user_is_vendor)){ $data['user_is_vendor'] = $alreadyStoredUserData->user_is_vendor; } if(!isset($data['virtuemart_vendor_id']) and !empty($alreadyStoredUserData->virtuemart_vendor_id)){ $data['virtuemart_vendor_id'] = $alreadyStoredUserData->virtuemart_vendor_id; } } unset($data['customer_number']); if(empty($alreadyStoredUserData->customer_number)){ //if(!class_exists('vmUserPlugin')) require(JPATH_VM_SITE.DS.'helpers'.DS.'vmuserplugin.php'); ///if(!$returnValues){ $data['customer_number'] = strtoupper(substr($data['username'],0,2)).substr(md5($data['username']),0,9); //We set this data so that vmshopper plugin know if they should set the customer nummer $data['customer_number_bycore'] = 1; //} } else { if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check("admin,storeadmin")) { $data['customer_number'] = $alreadyStoredUserData->customer_number; } } if($app->isSite()){ unset($data['perms']); if(!empty($alreadyStoredUserData->perms)){ $data['perms'] = $alreadyStoredUserData->perms; } else { $data['perms'] = 'shopper'; } } else { } if($trigger){ JPluginHelper::importPlugin('vmshopper'); $dispatcher = JDispatcher::getInstance(); $plg_datas = $dispatcher->trigger('plgVmOnUserStore',array(&$data)); foreach($plg_datas as $plg_data){ // $data = array_merge($plg_data,$data); } } $usertable -> bindChecknStore($data); $errors = $usertable->getErrors(); foreach($errors as $error){ $this->setError($error); vmError('storing user adress data'.$error); $noError = false; } if(Permissions::getInstance()->check("admin,storeadmin")) { $shoppergroupmodel = VmModel::getModel('ShopperGroup'); if(empty($this->_defaultShopperGroup)){ $this->_defaultShopperGroup = $shoppergroupmodel->getDefault(0); } if(empty($data['virtuemart_shoppergroup_id']) or $data['virtuemart_shoppergroup_id']==$this->_defaultShopperGroup->virtuemart_shoppergroup_id){ $data['virtuemart_shoppergroup_id'] = array(); } // Bind the form fields to the table if(!empty($data['virtuemart_shoppergroup_id'])){ $shoppergroupData = array('virtuemart_user_id'=>$this->_id,'virtuemart_shoppergroup_id'=>$data['virtuemart_shoppergroup_id']); $user_shoppergroups_table = $this->getTable('vmuser_shoppergroups'); $shoppergroupData = $user_shoppergroups_table -> bindChecknStore($shoppergroupData); $errors = $user_shoppergroups_table->getErrors(); foreach($errors as $error){ $this->setError($error); vmError('Set shoppergroup '.$error); $noError = false; } } } if($trigger){ $plg_datas = $dispatcher->trigger('plgVmAfterUserStore',array($data)); foreach($plg_datas as $plg_data){ $data = array_merge($plg_data); } } return $noError; } public function storeVendorData($data){ if($data['user_is_vendor']){ $vendorModel = VmModel::getModel('vendor'); //TODO Attention this is set now to virtuemart_vendor_id=1, because using a vendor with different id then 1 is not completly supported and can lead to bugs //So we disable the possibility to store vendors not with virtuemart_vendor_id = 1 if(Vmconfig::get('multix','none')=='none' ){ $data['virtuemart_vendor_id'] = 1; vmdebug('no multivendor, set virtuemart_vendor_id = 1'); } $vendorModel->setId($data['virtuemart_vendor_id']); if(empty($data['vendor_store_name']) and !empty($data['company'])) $data['vendor_store_name'] = $data['company']; if (!$vendorModel->store($data)) { vmError('storeVendorData '.$vendorModel->getError()); vmdebug('Error storing vendor',$vendorModel); return false; } } return true; } /** * Take a data array and save any address info found in the array. * * @author unknown, oscar, max milbers * @param array $data (Posted) user data * @param sting $_table Table name to write to, null (default) not to write to the database * @param boolean $_cart Attention, this was deleted, the address to cart is now done in the controller (True to write to the session (cart)) * @return boolean True if the save was successful, false otherwise. */ function storeAddress(&$data){ // if(empty($data['address_type'])){ // vmError('storeAddress no address_type given'); // return false; // } $user =JFactory::getUser(); $userinfo = $this->getTable('userinfos'); if($data['address_type'] == 'BT'){ if(isset($data['virtuemart_userinfo_id']) and $data['virtuemart_userinfo_id']!=0){ $data['virtuemart_userinfo_id'] = (int)$data['virtuemart_userinfo_id']; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); if(!Permissions::getInstance()->check('admin')){ $userinfo->load($data['virtuemart_userinfo_id']); if($userinfo->virtuemart_user_id!=$user->id){ vmError('Hacking attempt as admin?','Hacking attempt storeAddress'); return false; } } } else { if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); //Todo multi-x, also vendors should be allowed to change the user address. if(!Permissions::getInstance()->check('admin')){ $userId = $user->id; } else { $userId = (int)$data['virtuemart_user_id']; } $q = 'SELECT `virtuemart_userinfo_id` FROM #__virtuemart_userinfos WHERE `virtuemart_user_id` = '.$userId.' AND `address_type` = "BT"'; $this->_db->setQuery($q); $total = $this->_db->loadResultArray(); if (count($total) > 0) { $data['virtuemart_userinfo_id'] = (int)$total[0]; } else { $data['virtuemart_userinfo_id'] = 0;//md5(uniqid($this->virtuemart_user_id)); } $userinfo->load($data['virtuemart_userinfo_id']); //unset($data['virtuemart_userinfo_id']); } if(!$this->validateUserData((array)$data,'BT')){ return false; } $userInfoData = self::_prepareUserFields($data, 'BT',$userinfo); //vmdebug('model user storeAddress',$data); if (!$userinfo->bindChecknStore($userInfoData)) { vmError('storeAddress '.$userinfo->getError()); } } // Check for fields with the the 'shipto_' prefix; that means a (new) shipto address. if($data['address_type'] == 'ST' or isset($data['shipto_address_type_name'])){ $dataST = array(); $_pattern = '/^shipto_/'; foreach ($data as $_k => $_v) { if (preg_match($_pattern, $_k)) { $_new = preg_replace($_pattern, '', $_k); $dataST[$_new] = $_v; } } $userinfo = $this->getTable('userinfos'); if(isset($dataST['virtuemart_userinfo_id']) and $dataST['virtuemart_userinfo_id']!=0){ $dataST['virtuemart_userinfo_id'] = (int)$dataST['virtuemart_userinfo_id']; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); if(!Permissions::getInstance()->check('admin')){ $userinfo->load($dataST['virtuemart_userinfo_id']); $user = JFactory::getUser(); if($userinfo->virtuemart_user_id!=$user->id){ vmError('Hacking attempt as admin?','Hacking attempt store address'); return false; } } } if(empty($userinfo->virtuemart_user_id)){ if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php'); if(!Permissions::getInstance()->check('admin')){ $dataST['virtuemart_user_id'] = $user->id; } else { if(isset($data['virtuemart_user_id'])){ $dataST['virtuemart_user_id'] = (int)$data['virtuemart_user_id']; } else { //Disadvantage is that admins should not change the ST address in the FE (what should never happen anyway.) $dataST['virtuemart_user_id'] = $user->id; } } } if(!$this->validateUserData((array)$dataST,'ST')){ return false; } $dataST['address_type'] = 'ST'; $userfielddata = self::_prepareUserFields($dataST, 'ST',$userinfo); if (!$userinfo->bindChecknStore($userfielddata)) { vmError($userinfo->getError()); } } return $userinfo->virtuemart_userinfo_id; } /** * Test userdata if valid * * @author Max Milbers * @param String if BT or ST * @param Object If given, an object with data address data that must be formatted to an array * @return redirectMsg, if there is a redirectMsg, the redirect should be executed after */ public function validateUserData($data,$type='BT') { if (!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'userfields.php'); $userFieldsModel = VmModel::getModel('userfields'); if ($type == 'BT') { $fieldtype = 'account'; }else { $fieldtype = 'shipment'; } $neededFields = $userFieldsModel->getUserFields( $fieldtype , array('required' => true, 'delimiters' => true, 'captcha' => true, 'system' => false) , array('delimiter_userinfo', 'name','username', 'password', 'password2', 'address_type_name', 'address_type', 'user_is_vendor', 'agreed')); $i = 0; $j = 0; $return = true; $required = 0; //$objSize = count($data); $missingFields = array(); foreach ($neededFields as $field) { //This is a special test for the virtuemart_state_id. There is the speciality that the virtuemart_state_id could be 0 but is valid. if ($field->name == 'virtuemart_state_id') { if (!class_exists('VirtueMartModelState')) require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'state.php'); if(!empty($data['virtuemart_country_id'])){ if(!isset($data['virtuemart_state_id'])) $data['virtuemart_state_id'] = 0; if (!$msg = VirtueMartModelState::testStateCountry($data['virtuemart_country_id'], $data['virtuemart_state_id'])) { //The state is invalid, so we set the state 0 here. $data['virtuemart_state_id'] = 0; vmdebug('State was not fitting to country, set to 0'); } else if(empty($data['virtuemart_state_id'])){ vmdebug('virtuemart_state_id is empty, but valid (country has not states, set to unrequired'); $field->required = false; } else { vmdebug('validateUserData my country '.$data['virtuemart_country_id'].' my state '.$data['virtuemart_state_id']); } } } if($field->required ){ $required++; if(empty($data[$field->name])){ $missingFields[] = JText::_($field->title); $i++; $return = false; } else if($data[$field->name] == $field->default){ $i++; } else { } } } if($i==$required) $return = -1; //vmdebug('my i '.$i.' my data size '.$required,$return,$data); if(!$return){ VmConfig::loadJLang('com_virtuemart_shoppers', true); foreach($missingFields as $fieldname){ vmInfo(JText::sprintf('COM_VIRTUEMART_MISSING_VALUE_FOR_FIELD',$fieldname) ); vmdebug(''); } } return $return; } function _prepareUserFields(&$data, $type,$userinfo = 0) { if(!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'userfields.php' ); $userFieldsModel = VmModel::getModel('userfields'); if ($type == 'ST') { $prepareUserFields = $userFieldsModel->getUserFields( 'shipment' , array() // Default toggles ); } else { // BT // The user is not logged in (anonymous), so we need tome extra fields $prepareUserFields = $userFieldsModel->getUserFields( 'account' , array() // Default toggles , array('delimiter_userinfo', 'name', 'username', 'password', 'password2', 'user_is_vendor') // Skips ); } $admin = false; if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(Permissions::getInstance()->check('admin','storeadmin')){ $admin = true; } // Format the data foreach ($prepareUserFields as $fld) { if(empty($data[$fld->name])) $data[$fld->name] = ''; if(!$admin and $fld->readonly){ $fldName = $fld->name; unset($data[$fldName]); if($userinfo!==0){ if(property_exists($userinfo,$fldName)){ //vmdebug('property_exists userinfo->$fldName '.$fldName,$userinfo); $data[$fldName] = $userinfo->$fldName; } else { vmError('Your tables seem to be broken, you have fields in your form which have no corresponding field in the db'); } } } else { $data[$fld->name] = $userFieldsModel->prepareFieldDataSave($fld, $data); } } return $data; } function getBTuserinfo_id($id = 0){ if(empty($this->_db)) $this->_db = JFactory::getDBO(); if($id == 0){ $id = $this->_id; //vmdebug('getBTuserinfo_id is '.$this->_id); } $q = 'SELECT `virtuemart_userinfo_id` FROM `#__virtuemart_userinfos` WHERE `virtuemart_user_id` = "' .(int)$id .'" AND `address_type`="BT" '; $this->_db->setQuery($q); return $this->_db->loadResult(); } /** * * @author Max Milbers */ function getUserInfoInUserFields($layoutName, $type,$uid,$cart=true,$isVendor=false ){ // if(!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'userfields.php' ); // $userFieldsModel = new VirtuemartModelUserfields(); $userFieldsModel = VmModel::getModel('userfields'); $prepareUserFields = $userFieldsModel->getUserFieldsFor( $layoutName, $type, $uid ); if($type=='ST'){ $preFix = 'shipto_'; } else { $preFix = ''; } /* * JUser or $this->_id is the logged user */ if(!empty($this->_data->JUser)){ $JUser = $this->_data->JUser; } else { $JUser = JUser::getInstance($this->_id); } $userFields = array(); if(!empty($uid)){ $data = $this->getTable('userinfos'); $data->load($uid); //vmdebug('$data',$data); if($data->virtuemart_user_id!==0 and !$isVendor){ if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(!Permissions::getInstance()->check("admin")) { if($data->virtuemart_user_id!=$this->_id){ vmError('Hacking attempt loading userinfo, you got logged'); echo 'Hacking attempt loading userinfo, you got logged'; return false; } } } if ($data->address_type != 'ST' ) { $BTuid = $uid; $data->name = $JUser->name; $data->email = $JUser->email; $data->username = $JUser->username; $data->address_type = 'BT'; } // vmdebug('getUserInfoInUserFields ',$data); } else { //New Address is filled here with the data of the cart (we are in the userview) if($cart){ if (!class_exists('VirtueMartCart')) require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); $cart = VirtueMartCart::getCart(); $adType = $type.'address'; if(empty($cart->$adType)){ $data = $cart->$type; if(empty($data)) $data = array(); if($JUser){ if(empty($data['name'])){ $data['name'] = $JUser->name; } if(empty($data['email'])){ $data['email'] = $JUser->email; } if(empty($data['username'])){ $data['username'] = $JUser->username; } if(empty($data['virtuemart_user_id'])){ $data['virtuemart_user_id'] = $JUser->id; } } } $data = (object)$data; } else { if($JUser){ if(empty($data['name'])){ $data['name'] = $JUser->name; } if(empty($data['email'])){ $data['email'] = $JUser->email; } if(empty($data['username'])){ $data['username'] = $JUser->username; } if(empty($data['virtuemart_user_id'])){ $data['virtuemart_user_id'] = $JUser->id; } $data = (object)$data; } else { $data = null; } } } $userFields[$uid] = $userFieldsModel->getUserFieldsFilled( $prepareUserFields ,$data ,$preFix ); return $userFields; } /** * This should store the userdata given in userfields * * @author Max Milbers */ function storeUserDataByFields($data,$type, $toggles, $skips){ if(!class_exists('VirtueMartModelUserfields')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'userfields.php' ); $userFieldsModel = VmModel::getModel('userfields'); $prepareUserFields = $userFieldsModel->getUserFields( $type, $toggles, $skips ); // Format the data foreach ($prepareUserFields as $_fld) { if(empty($data[$_fld->name])) $data[$_fld->name] = ''; $data[$_fld->name] = $userFieldsModel->prepareFieldDataSave($_fld,$data); } $this->store($data); return true; } /** * This uses the shopFunctionsF::renderAndSendVmMail function, which uses a controller and task to render the content * and sents it then. * * * @author Oscar van Eijk * @author Max Milbers * @author Christopher Roussel * @author Valérie Isaksen */ private function sendRegistrationEmail($user, $password, $doUserActivation){ if(!class_exists('shopFunctionsF')) require(JPATH_VM_SITE.DS.'helpers'.DS.'shopfunctionsf.php'); $vars = array('user' => $user); // Send registration confirmation mail $password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email $vars['password'] = $password; if ($doUserActivation) { jimport('joomla.user.helper'); if(JVM_VERSION === 2) { $com_users = 'com_users'; $activationLink = 'index.php?option='.$com_users.'&task=registration.activate&token='.$user->get('activation'); } else { $com_users = 'com_user'; $activationLink = 'index.php?option='.$com_users.'&task=activate&activation='.$user->get('activation'); } $vars['activationLink'] = $activationLink; } $vars['doVendor']=true; // public function renderMail ($viewName, $recipient, $vars=array(),$controllerName = null) shopFunctionsF::renderMail('user', $user->get('email'), $vars); } /** * Delete all record ids selected * * @return boolean True is the remove was successful, false otherwise. */ function remove($userIds) { if(!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'permissions.php'); if(Permissions::getInstance()->check('admin','storeadmin')) { $userInfo = $this->getTable('userinfos'); $vm_shoppergroup_xref = $this->getTable('vmuser_shoppergroups'); $vmusers = $this->getTable('vmusers'); $_status = true; foreach($userIds as $userId) { $_JUser = JUser::getInstance($userId); if ($this->getSuperAdminCount() <= 1) { // Prevent deletion of the only Super Admin //$_u = JUser::getInstance($userId); if ($_JUser->get('gid') == __SUPER_ADMIN_GID) { vmError(JText::_('COM_VIRTUEMART_USER_ERR_LASTSUPERADMIN')); $_status = false; continue; } } if(Permissions::getInstance()->check('storeadmin')) { if ($_JUser->get('gid') == __SUPER_ADMIN_GID) { vmError(JText::_('COM_VIRTUEMART_USER_ERR_LASTSUPERADMIN')); $_status = false; continue; } } if (!$userInfo->delete($userId)) { vmError($userInfo->getError()); return false; } if (!$vm_shoppergroup_xref->delete($userId)) { vmError($vm_shoppergroup_xref->getError()); // Signal but continue $_status = false; continue; } if (!$vmusers->delete($userId)) { vmError($vmusers->getError()); // Signal but continue $_status = false; continue; } if (!$_JUser->delete()) { vmError($_JUser->getError()); $_status = false; continue; } } } return $_status; } function removeAddress($virtuemart_userinfo_id){ $db = JFactory::getDBO(); if ( isset($virtuemart_userinfo_id) and $this->_id != 0 ) { //$userModel -> deleteAddressST(); $q = 'DELETE FROM #__virtuemart_userinfos WHERE virtuemart_user_id="'. $this->_id .'" AND virtuemart_userinfo_id="'. (int)$virtuemart_userinfo_id .'"'; $db->setQuery($q); if($db->query()){ vmInfo('Address has been successfully deleted.'); return true; } } return false; } /** * Retrieve a list of users from the database. * * @author Max Milbers * @return object List of user objects */ function getUserList() { //$select = ' * '; //$joinedTables = ' FROM #__users AS ju LEFT JOIN #__virtuemart_vmusers AS vmu ON ju.id = vmu.virtuemart_user_id'; $search = JRequest::getString('search', false); $tableToUse = JRequest::getString('searchTable','juser'); $where = ''; if ($search) { $where = ' WHERE '; $searchArray = array('ju.name','username','email','perms','usertype','shopper_group_name'); if($tableToUse!='juser'){ if(!class_exists('TableUserinfos'))require(JPATH_VM_ADMINISTRATOR.DS.'tables'.DS.'userinfos.php'); $db = JFactory::getDbo(); $userfieldTable = new TableUserinfos($db); $userfieldFields = get_object_vars($userfieldTable); $userFieldSearchArray = array('company','first_name','last_name'); //We must validate if the userfields actually exists, they could be removed $userFieldsValid = array(); foreach($userFieldSearchArray as $ufield){ if(array_key_exists($ufield,$userfieldFields)){ $userFieldsValid[] = $ufield; } } $searchArray = array_merge($userFieldsValid,$searchArray); } $search = str_replace(' ','%',$this->_db->getEscaped( $search, true )); foreach($searchArray as $field){ $where.= ' '.$field.' LIKE "%'.$search.'%" OR '; } $where = substr($where,0,-3); } $select = ' ju.id AS id , ju.name AS name , ju.username AS username , ju.email AS email , IFNULL(vmu.user_is_vendor,"0") AS is_vendor , IFNULL(sg.shopper_group_name, "") AS shopper_group_name '; if ($search) { if($tableToUse!='juser'){ $select .= ' , ui.name as uiname '; } foreach($searchArray as $ufield){ $select .= ' , '.$ufield; } } $joinedTables = ' FROM #__users AS ju LEFT JOIN #__virtuemart_vmusers AS vmu ON ju.id = vmu.virtuemart_user_id LEFT JOIN #__virtuemart_vmuser_shoppergroups AS vx ON ju.id = vx.virtuemart_user_id LEFT JOIN #__virtuemart_shoppergroups AS sg ON vx.virtuemart_shoppergroup_id = sg.virtuemart_shoppergroup_id '; if ($search and $tableToUse!='juser') { $joinedTables .= ' LEFT JOIN #__virtuemart_userinfos AS ui ON ui.virtuemart_user_id = vmu.virtuemart_user_id'; } return $this->_data = $this->exeSortSearchListQuery(0,$select,$joinedTables,$where,' GROUP BY ju.id',$this->_getOrdering()); } /** * If a filter was set, get the SQL WHERE clase * * @return string text to add to the SQL statement */ function _getFilter() { if ($search = JRequest::getString('search', false)) { $search = '"%' . $this->_db->getEscaped( $search, true ) . '%"' ; //$search = $this->_db->Quote($search, false); $searchArray = array('name','username','email','perms','usertype','shopper_group_name'); $where = ' WHERE '; foreach($searchArray as $field){ $where.= ' `'.$field.'` LIKE '.$search.' OR '; } $where = substr($where,0,-3); //$where = ' WHERE `name` LIKE '.$search.' OR `username` LIKE ' .$search.' OR `email` LIKE ' .$search.' OR `perms` LIKE ' .$search.' OR `usertype` LIKE ' .$search.' OR `shopper_group_name` LIKE ' .$search; return ($where); } return (''); } /** * Retrieve a single address for a user * * @param $_uid int User ID * @param $_virtuemart_userinfo_id string Optional User Info ID * @param $_type string, addess- type, ST (ShipTo, default) or BT (BillTo). Empty string to ignore */ function getUserAddressList($_uid = 0, $_type = 'ST',$_virtuemart_userinfo_id = -1){ //Todo, add perms, allow admin to see 0 entries. if($_uid==0 and $this->_id==0){ return array(); } $_q = 'SELECT * FROM #__virtuemart_userinfos WHERE virtuemart_user_id="' . (($_uid==0)?$this->_id:(int)$_uid) .'"'; if ($_virtuemart_userinfo_id !== -1) { $_q .= ' AND virtuemart_userinfo_id="'.(int)$_virtuemart_userinfo_id.'"'; } else { if ($_type !== '') { $_q .= ' AND address_type="'.$_type.'"'; } } // vmdebug('getUserAddressList query '.$_q); return ($this->_getList($_q)); } /** * Retrieves the Customer Number of the user specified by ID * * @param int $_id User ID * @return string Customer Number */ private $customer_number = 0; public function getCustomerNumberById() { if($this->customer_number===0){ $_q = "SELECT `customer_number` FROM `#__virtuemart_vmusers` " ."WHERE `virtuemart_user_id`='" . $this->_id . "' "; $_r = $this->_getList($_q); if(!empty($_r[0])){ $this->customer_number = $_r[0]->customer_number; }else { $this->customer_number = false; } } return $this->customer_number; } /** * Get the number of active Super Admins * * @return integer */ function getSuperAdminCount() { $this->_db->setQuery('SELECT COUNT(id) FROM #__users' . ' WHERE usertype = ' . __SUPER_ADMIN_GID . ' AND block = 0'); return ($this->_db->loadResult()); } /** * Return a list of Joomla ACL groups. * * The returned object list includes a group anme and a group name with spaces * prepended to the name for displaying an indented tree. * * @author RickG * @return ObjectList List of acl group objects. */ function getAclGroupIndentedTree() { //TODO check this out if (JVM_VERSION===1) { $name = 'name'; $as = '` AS `title`'; $table = '#__core_acl_aro_groups'; $and = 'AND `parent`.`lft` > 2 '; } else { $name = 'title'; $as = '`'; $table = '#__usergroups'; $and = ''; } //Ugly thing, produces Select_full_join $query = 'SELECT `node`.`' . $name . $as . ', CONCAT(REPEAT("   ", (COUNT(`parent`.`' . $name . '`) - 1)), `node`.`' . $name . '`) AS `text` '; $query .= 'FROM `' . $table . '` AS node, `' . $table . '` AS parent '; $query .= 'WHERE `node`.`lft` BETWEEN `parent`.`lft` AND `parent`.`rgt` '; $query .= $and; $query .= 'GROUP BY `node`.`' . $name . '` '; $query .= ' ORDER BY `node`.`lft`'; $this->_db->setQuery($query); //$app = JFactory::getApplication(); //$app -> enqueueMessage($this->_db->getQuery()); $objlist = $this->_db->loadObjectList(); // vmdebug('getAclGroupIndentedTree',$objlist); return $objlist; } } //No Closing tag default.php000066600000044565151372131610006723 0ustar00 * @since 2.5.4 */ class JoomlaupdateModelDefault extends JModelLegacy { /** * Detects if the Joomla! update site currently in use matches the one * configured in this component. If they don't match, it changes it. * * @return void * * @since 2.5.4 */ public function applyUpdateSite() { // Determine the intended update URL $params = JComponentHelper::getParams('com_joomlaupdate'); switch ($params->get('updatesource', 'nochange')) { // "Long Term Support (LTS) branch - Recommended" case 'lts': $updateURL = 'http://update.joomla.org/core/list.xml'; break; // "Short term support (STS) branch" case 'sts': $updateURL = 'http://update.joomla.org/core/sts/list_sts.xml'; break; // "Testing" case 'testing': $updateURL = 'http://update.joomla.org/core/test/list_test.xml'; break; // "Custom" case 'custom': $updateURL = $params->get('customurl', ''); break; // "Do not change" case 'nochange': default: return; break; } $db = $this->getDbo(); $query = $db->getQuery(true) ->select($db->nq('us') . '.*') ->from( $db->nq('#__update_sites_extensions') . ' AS ' . $db->nq('map') ) ->innerJoin( $db->nq('#__update_sites') . ' AS ' . $db->nq('us') . ' ON (' . $db->nq('us') . '.' . $db->nq('update_site_id') . ' = ' . $db->nq('map') . '.' . $db->nq('update_site_id') . ')' ) ->where( $db->nq('map') . '.' . $db->nq('extension_id') . ' = ' . $db->q(700) ); $db->setQuery($query); $update_site = $db->loadObject(); if ($update_site->location != $updateURL) { // Modify the database record $update_site->last_check_timestamp = 0; $update_site->location = $updateURL; $db->updateObject('#__update_sites', $update_site, 'update_site_id'); // Remove cached updates $query = $db->getQuery(true) ->delete($db->nq('#__updates')) ->where($db->nq('extension_id').' = '.$db->q('700')); $db->setQuery($query); $db->query(); } } /** * Makes sure that the Joomla! update cache is up-to-date * * @param bool $force Force reload, ignoring the cache timeout * * @return void * * @since 2.5.4 */ public function refreshUpdates($force = false) { if ($force) { $cache_timeout = 0; } else { $update_params = JComponentHelper::getParams('com_installer'); $cache_timeout = $update_params->get('cachetimeout', 6, 'int'); $cache_timeout = 3600 * $cache_timeout; } $updater = JUpdater::getInstance(); $results = $updater->findUpdates(700, $cache_timeout); } /** * Returns an array with the Joomla! update information * * @return array * * @since 2.5.4 */ public function getUpdateInformation() { // Initialise the return array $ret = array( 'installed' => JVERSION, 'latest' => null, 'object' => null ); // Fetch the update information from the database $db = $this->getDbo(); $query = $db->getQuery(true) ->select('*') ->from($db->nq('#__updates')) ->where($db->nq('extension_id') . ' = ' . $db->q(700)); $db->setQuery($query); $updateObject = $db->loadObject(); if (is_null($updateObject)) { $ret['latest'] = JVERSION; return $ret; } else { $ret['latest'] = $updateObject->version; } // Fetch the full udpate details from the update details URL jimport('joomla.updater.update'); $update = new JUpdate; $update->loadFromXML($updateObject->detailsurl); // Pass the update object if($ret['latest'] == JVERSION) { $ret['object'] = null; } else { $ret['object'] = $update; } return $ret; } /** * Returns an array with the configured FTP options * * @return array * * @since 2.5.4 */ public function getFTPOptions() { $config = JFactory::getConfig(); return array( 'host' => $config->get('ftp_host'), 'port' => $config->get('ftp_port'), 'username' => $config->get('ftp_user'), 'password' => $config->get('ftp_pass'), 'directory' => $config->get('ftp_root'), 'enabled' => $config->get('ftp_enable'), ); } /** * Downloads the update package to the site * * @return bool|string False on failure, basename of the file in any other case * * @since 2.5.4 */ public function download() { $updateInfo = $this->getUpdateInformation(); $packageURL = $updateInfo['object']->downloadurl->_data; $basename = basename($packageURL); // Find the path to the temp directory and the local package $jreg = JFactory::getConfig(); $tempdir = $jreg->getValue('config.tmp_path'); $target = $tempdir . '/' . $basename; // Do we have a cached file? jimport('joomla.filesystem.file'); $exists = JFile::exists($target); if (!$exists) { // Not there, let's fetch it return $this->downloadPackage($packageURL, $target); } else { // Is it a 0-byte file? If so, re-download please. $filesize = @filesize($target); if(empty($filesize)) return $this->downloadPackage($packageURL, $target); // Yes, it's there, skip downloading return $basename; } } /** * Downloads a package file to a specific directory * * @param string $url The URL to download from * @param string $target The directory to store the file * * @return boolean True on success * * @since 2.5.4 */ protected function downloadPackage($url, $target) { JLoader::import('helpers.download', JPATH_COMPONENT_ADMINISTRATOR); $result = AdmintoolsHelperDownload::download($url, $target); if(!$result) { return false; } else { return basename($target); } } /** * @since 2.5.4 */ public function createRestorationFile($basename = null) { // Get a password jimport('joomla.user.helper'); $password = JUserHelper::genRandomPassword(32); JFactory::getApplication()->setUserState('com_joomlaupdate.password', $password); // Do we have to use FTP? $method = JRequest::getCmd('method', 'direct'); // Get the absolute path to site's root $siteroot = JPATH_SITE; // If the package name is not specified, get it from the update info if (empty($basename)) { $updateInfo = $this->getUpdateInformation(); $packageURL = $updateInfo['object']->downloadurl->_data; $basename = basename($packageURL); } // Get the package name $tempdir = JFactory::getConfig()->getValue('config.tmp_path'); $file = $tempdir . '/' . $basename; $filesize = @filesize($file); JFactory::getApplication()->setUserState('com_joomlaupdate.password', $password); JFactory::getApplication()->setUserState('com_joomlaupdate.filesize', $filesize); $data = " '$password', 'kickstart.tuning.max_exec_time' => '5', 'kickstart.tuning.run_time_bias' => '75', 'kickstart.tuning.min_exec_time' => '0', 'kickstart.procengine' => '$method', 'kickstart.setup.sourcefile' => '$file', 'kickstart.setup.destdir' => '$siteroot', 'kickstart.setup.restoreperms' => '0', 'kickstart.setup.filetype' => 'zip', 'kickstart.setup.dryrun' => '0' ENDDATA; if ($method == 'ftp') { // Fetch the FTP parameters from the request. Note: The password should be // allowed as raw mode, otherwise something like !@43H% would be // sanitised to !@43H% which is just plain wrong. $ftp_host = JRequest::getVar('ftp_host',''); $ftp_port = JRequest::getVar('ftp_port', '21'); $ftp_user = JRequest::getVar('ftp_user', ''); $ftp_pass = JRequest::getVar('ftp_pass', '', 'default', 'none', 2); $ftp_root = JRequest::getVar('ftp_root', ''); // Is the tempdir really writable? $writable = @is_writeable($tempdir); if($writable) { // Let's be REALLY sure $fp = @fopen($tempdir.'/test.txt','w'); if($fp === false) { $writable = false; } else { fclose($fp); unlink($tempdir.'/test.txt'); } } // If the tempdir is not writable, create a new writable subdirectory if(!$writable) { jimport('joomla.client.ftp'); jimport('joomla.client.helper'); jimport('joomla.filesystem.folder'); $FTPOptions = JClientHelper::getCredentials('ftp'); $ftp = & JFTP::getInstance($FTPOptions['host'], $FTPOptions['port'], null, $FTPOptions['user'], $FTPOptions['pass']); $dest = JPath::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $tempdir.'/admintools'), '/'); if(!@mkdir($tempdir.'/admintools')) $ftp->mkdir($dest); if(!@chmod($tempdir.'/admintools', 511)) $ftp->chmod($dest, 511); $tempdir .= '/admintools'; } // Just in case the temp-directory was off-root, try using the default tmp directory $writable = @is_writeable($tempdir); if(!$writable) { $tempdir = JPATH_ROOT.'/tmp'; // Does the JPATH_ROOT/tmp directory exist? if(!is_dir($tempdir)) { jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.file'); JFolder::create($tempdir, 511); JFile::write($tempdir.'/.htaccess',"order deny, allow\ndeny from all\nallow from none\n"); } // If it exists and it is unwritable, try creating a writable admintools subdirectory if(!is_writable($tempdir)) { jimport('joomla.client.ftp'); jimport('joomla.client.helper'); jimport('joomla.filesystem.folder'); $FTPOptions = JClientHelper::getCredentials('ftp'); $ftp = & JFTP::getInstance($FTPOptions['host'], $FTPOptions['port'], null, $FTPOptions['user'], $FTPOptions['pass']); $dest = JPath::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $tempdir.'/admintools'), '/'); if(!@mkdir($tempdir.'/admintools')) $ftp->mkdir($dest); if(!@chmod($tempdir.'/admintools', 511)) $ftp->chmod($dest, 511); $tempdir .= '/admintools'; } } // If we still have no writable directory, we'll try /tmp and the system's temp-directory $writable = @is_writeable($tempdir); if(!$writable) { if(@is_dir('/tmp') && @is_writable('/tmp')) { $tempdir = '/tmp'; } else { // Try to find the system temp path $tmpfile = @tempnam("dummy",""); $systemp = @dirname($tmpfile); @unlink($tmpfile); if(!empty($systemp)) { if(@is_dir($systemp) && @is_writable($systemp)) { $tempdir = $systemp; } } } } $data.=<< '0', 'kickstart.ftp.passive' => '1', 'kickstart.ftp.host' => '$ftp_host', 'kickstart.ftp.port' => '$ftp_port', 'kickstart.ftp.user' => '$ftp_user', 'kickstart.ftp.pass' => '$ftp_pass', 'kickstart.ftp.dir' => '$ftp_root', 'kickstart.ftp.tempdir' => '$tempdir' ENDDATA; } $data .= ');'; // Remove the old file, if it's there... jimport('joomla.filesystem.file'); $configpath = JPATH_COMPONENT_ADMINISTRATOR . '/restoration.php'; if( JFile::exists($configpath) ) { JFile::delete($configpath); } // Write new file. First try with JFile. $result = JFile::write( $configpath, $data ); // In case JFile used FTP but direct access could help if(!$result) { if(function_exists('file_put_contents')) { $result = @file_put_contents($configpath, $data); if($result !== false) $result = true; } else { $fp = @fopen($configpath, 'wt'); if($fp !== false) { $result = @fwrite($fp, $data); if($result !== false) $result = true; @fclose($fp); } } } return $result; } /** * Runs the schema update SQL files, the PHP update script and updates the * manifest cache and #__extensions entry. Essentially, it is identical to * JInstallerFile::install() without the file copy. * * @return boolean True on success * * @since 2.5.4 */ public function finaliseUpgrade() { jimport('joomla.installer.install'); $installer = JInstaller::getInstance(); $installer->setPath('source', JPATH_ROOT); $installer->setPath('extension_root', JPATH_ROOT); if (!$installer->setupInstall()) { $installer->abort(JText::_('JLIB_INSTALLER_ABORT_DETECTMANIFEST')); return false; } $installer->extension = JTable::getInstance('extension'); $installer->extension->load(700); $installer->setAdapter($installer->extension->type); $manifest = $installer->getManifest(); $manifestPath = JPath::clean($installer->getPath('manifest')); $element = preg_replace('/\.xml/', '', basename($manifestPath)); // Run the script file $scriptElement = $manifest->scriptfile; $manifestScript = (string) $manifest->scriptfile; if ($manifestScript) { $manifestScriptFile = JPATH_ROOT . '/' . $manifestScript; if (is_file($manifestScriptFile)) { // load the file include_once $manifestScriptFile; } $classname = 'JoomlaInstallerScript'; if (class_exists($classname)) { $manifestClass = new $classname($this); } } ob_start(); ob_implicit_flush(false); if ($manifestClass && method_exists($manifestClass, 'preflight')) { if ($manifestClass->preflight('update', $this) === false) { $installer->abort(JText::_('JLIB_INSTALLER_ABORT_FILE_INSTALL_CUSTOM_INSTALL_FAILURE')); return false; } } $msg = ob_get_contents(); // create msg object; first use here ob_end_clean(); // Get a database connector object $db = JFactory::getDbo(); // Check to see if a file extension by the same name is already installed // If it is, then update the table because if the files aren't there // we can assume that it was (badly) uninstalled // If it isn't, add an entry to extensions $query = $db->getQuery(true); $query->select($query->qn('extension_id')) ->from($query->qn('#__extensions')); $query->where($query->qn('type') . ' = ' . $query->q('file')) ->where($query->qn('element') . ' = ' . $query->q('joomla')); $db->setQuery($query); try { $db->Query(); } catch (RuntimeException $e) { // Install failed, roll back changes $installer->abort( JText::sprintf('JLIB_INSTALLER_ABORT_FILE_ROLLBACK', JText::_('JLIB_INSTALLER_UPDATE'), $db->stderr(true)) ); return false; } $id = $db->loadResult(); $row = JTable::getInstance('extension'); if ($id) { // Load the entry and update the manifest_cache $row->load($id); // Update name $row->set('name', 'files_joomla'); // Update manifest $row->manifest_cache = $installer->generateManifestCache(); if (!$row->store()) { // Install failed, roll back changes $installer->abort( JText::sprintf('JLIB_INSTALLER_ABORT_FILE_ROLLBACK', JText::_('JLIB_INSTALLER_UPDATE'), $db->stderr(true)) ); return false; } } else { // Add an entry to the extension table with a whole heap of defaults $row->set('name', 'files_joomla'); $row->set('type', 'file'); $row->set('element', 'joomla'); // There is no folder for files so leave it blank $row->set('folder', ''); $row->set('enabled', 1); $row->set('protected', 0); $row->set('access', 0); $row->set('client_id', 0); $row->set('params', ''); $row->set('system_data', ''); $row->set('manifest_cache', $installer->generateManifestCache()); if (!$row->store()) { // Install failed, roll back changes $installer->abort(JText::sprintf('JLIB_INSTALLER_ABORT_FILE_INSTALL_ROLLBACK', $db->stderr(true))); return false; } // Set the insert id $row->set('extension_id', $db->insertid()); // Since we have created a module item, we add it to the installation step stack // so that if we have to rollback the changes we can undo it. $installer->pushStep(array('type' => 'extension', 'extension_id' => $row->extension_id)); } /* * Let's run the queries for the file */ if ($manifest->update) { $result = $installer->parseSchemaUpdates($manifest->update->schemas, $row->extension_id); if ($result === false) { // Install failed, rollback changes $installer->abort(JText::sprintf('JLIB_INSTALLER_ABORT_FILE_UPDATE_SQL_ERROR', $db->stderr(true))); return false; } } // Start Joomla! 1.6 ob_start(); ob_implicit_flush(false); if ($manifestClass && method_exists($manifestClass, 'update')) { if ($manifestClass->update($installer) === false) { // Install failed, rollback changes $installer->abort(JText::_('JLIB_INSTALLER_ABORT_FILE_INSTALL_CUSTOM_INSTALL_FAILURE')); return false; } } $msg .= ob_get_contents(); // append messages ob_end_clean(); // Lastly, we will copy the manifest file to its appropriate place. $manifest = array(); $manifest['src'] = $installer->getPath('manifest'); $manifest['dest'] = JPATH_MANIFESTS . '/files/' . basename($installer->getPath('manifest')); if (!$installer->copyFiles(array($manifest), true)) { // Install failed, rollback changes $installer->abort(JText::_('JLIB_INSTALLER_ABORT_FILE_INSTALL_COPY_SETUP')); return false; } // Clobber any possible pending updates $update = JTable::getInstance('update'); $uid = $update->find( array('element' => $element, 'type' => 'file', 'client_id' => '', 'folder' => '') ); if ($uid) { $update->delete($uid); } // And now we run the postflight ob_start(); ob_implicit_flush(false); if ($manifestClass && method_exists($manifestClass, 'postflight')) { $manifestClass->postflight('update', $this); } $msg .= ob_get_contents(); // append messages ob_end_clean(); if ($msg != '') { $installer->set('extension_message', $msg); } return true; } /** * Removes the extracted package file * * @return void * * @since 2.5.4 */ public function cleanUp() { jimport('joomla.filesystem.file'); // Remove the update package $jreg = JFactory::getConfig(); $tempdir = $jreg->getValue('config.tmp_path'); $file = JFactory::getApplication()->getUserState('com_joomlaupdate.file', null); $target = $tempdir.'/'.$file; if (!@unlink($target)) { jimport('joomla.filesystem.file'); JFile::delete($target); } // Remove the restoration.php file $target = JPATH_COMPONENT_ADMINISTRATOR . '/restoration.php'; if (!@unlink($target)) { JFile::delete($target); } // Remove joomla.xml from the site's root $target = JPATH_ROOT . '/joomla.xml'; if (!@unlink($target)) { JFile::delete($target); } // Unset the update filename from the session JFactory::getApplication()->setUserState('com_joomlaupdate.file', null); } } fields/categoryparent.php000066600000011636151372253730011575 0ustar00element['name']; // Let's get the id for the current item, either category or content item. $jinput = JFactory::getApplication()->input; // For categories the old category is the category id 0 for new category. if ($this->element['parent']) { $oldCat = $jinput->get('id',0); $oldParent = $this->form->getValue($name); } else // For items the old category is the category they are in when opened or 0 if new. { $thisItem = $jinput->get('id',0); $oldCat = $this->form->getValue($name); } $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('a.id AS value, a.title AS text, a.level'); $query->from('#__categories AS a'); $query->join('LEFT', $db->quoteName('#__categories').' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); // Filter by the type if ($extension = $this->form->getValue('extension')) { $query->where('(a.extension = '.$db->quote($extension).' OR a.parent_id = 0)'); } if ($this->element['parent']) { // Prevent parenting to children of this item. if ($id = $this->form->getValue('id')) { $query->join('LEFT', $db->quoteName('#__categories').' AS p ON p.id = '.(int) $id); $query->where('NOT(a.lft >= p.lft AND a.rgt <= p.rgt)'); $rowQuery = $db->getQuery(true); $rowQuery->select('a.id AS value, a.title AS text, a.level, a.parent_id'); $rowQuery->from('#__categories AS a'); $rowQuery->where('a.id = ' . (int) $id); $db->setQuery($rowQuery); $row = $db->loadObject(); } } $query->where('a.published IN (0,1)'); $query->group('a.id, a.title, a.level, a.lft, a.rgt, a.extension, a.parent_id'); $query->order('a.lft ASC'); // Get the options. $db->setQuery($query); $options = $db->loadObjectList(); // Check for a database error. if ($db->getErrorNum()) { JError::raiseWarning(500, $db->getErrorMsg()); } // Pad the option text with spaces using depth level as a multiplier. for ($i = 0, $n = count($options); $i < $n; $i++) { // Translate ROOT if ($options[$i]->level == 0) { $options[$i]->text = JText::_('JGLOBAL_ROOT_PARENT'); } $options[$i]->text = str_repeat('- ', $options[$i]->level).$options[$i]->text; } // Initialise variables. // Get the current user object. $user = JFactory::getUser(); // For new items we want a list of categories you are allowed to create in. if ($oldCat == 0) { foreach ($options as $i => $option) { // To take save or create in a category you need to have create rights for that category // unless the item is already in that category. // Unset the option if the user isn't authorised for it. In this field assets are always categories. if ($user->authorise('core.create', $extension . '.category.' . $option->value) != true ) { unset($options[$i]); } } } // If you have an existing category id things are more complex. else { //$categoryOld = $this->form->getValue($name); foreach ($options as $i => $option) { // If you are only allowed to edit in this category but not edit.state, you should not get any // option to change the category parent for a category or the category for a content item, // but you should be able to save in that category. if ($user->authorise('core.edit.state', $extension . '.category.' . $oldCat) != true) { if ($option->value != $oldCat) {echo 'y'; unset($options[$i]); } } // However, if you can edit.state you can also move this to another category for which you have // create permission and you should also still be able to save in the current category. elseif (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) && $option->value != $oldCat) {echo 'x'; unset($options[$i]); } } } if (isset($row) && !isset($options[0])) { if ($row->parent_id == '1') { $parent = new stdClass(); $parent->text = JText::_('JGLOBAL_ROOT_PARENT'); array_unshift($options, $parent); } } // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; } } fields/categoryedit.php000066600000015714151372253730011232 0ustar00element['published']? $this->element['published'] : array(0,1); $name = (string) $this->element['name']; // Let's get the id for the current item, either category or content item. $jinput = JFactory::getApplication()->input; // Load the category options for a given extension. // For categories the old category is the category id or 0 for new category. if ($this->element['parent'] || $jinput->get('option') == 'com_categories') { $oldCat = $jinput->get('id', 0); $oldParent = $this->form->getValue($name, 0); $extension = $this->element['extension'] ? (string) $this->element['extension'] : (string) $jinput->get('extension','com_content'); } else // For items the old category is the category they are in when opened or 0 if new. { $thisItem = $jinput->get('id',0); $oldCat = $this->form->getValue($name, 0); $extension = $this->element['extension'] ? (string) $this->element['extension'] : (string) $jinput->get('option','com_content'); } $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('a.id AS value, a.title AS text, a.level, a.published'); $query->from('#__categories AS a'); $query->join('LEFT', $db->quoteName('#__categories').' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); // Filter by the extension type if ($this->element['parent'] == true || $jinput->get('option') == 'com_categories') { $query->where('(a.extension = '.$db->quote($extension).' OR a.parent_id = 0)'); } else { $query->where('(a.extension = '.$db->quote($extension).')'); } // If parent isn't explicitly stated but we are in com_categories assume we want parents if ($oldCat != 0 && ($this->element['parent'] == true || $jinput->get('option') == 'com_categories')) { // Prevent parenting to children of this item. // To rearrange parents and children move the children up, not the parents down. $query->join('LEFT', $db->quoteName('#__categories').' AS p ON p.id = '.(int) $oldCat); $query->where('NOT(a.lft >= p.lft AND a.rgt <= p.rgt)'); $rowQuery = $db->getQuery(true); $rowQuery->select('a.id AS value, a.title AS text, a.level, a.parent_id'); $rowQuery->from('#__categories AS a'); $rowQuery->where('a.id = ' . (int) $oldCat); $db->setQuery($rowQuery); $row = $db->loadObject(); } // Filter on the published state if (is_numeric($published)) { $query->where('a.published = ' . (int) $published); } elseif (is_array($published)) { JArrayHelper::toInteger($published); $query->where('a.published IN (' . implode(',', $published) . ')'); } $query->group('a.id, a.title, a.level, a.lft, a.rgt, a.extension, a.parent_id, a.published'); $query->order('a.lft ASC'); // Get the options. $db->setQuery($query); $options = $db->loadObjectList(); // Check for a database error. if ($db->getErrorNum()) { JError::raiseWarning(500, $db->getErrorMsg()); } // Pad the option text with spaces using depth level as a multiplier. for ($i = 0, $n = count($options); $i < $n; $i++) { // Translate ROOT if ($this->element['parent'] == true || $jinput->get('option') == 'com_categories') { if ($options[$i]->level == 0) { $options[$i]->text = JText::_('JGLOBAL_ROOT_PARENT'); } } if ($options[$i]->published == 1) { $options[$i]->text = str_repeat('- ', $options[$i]->level). $options[$i]->text ; } else { $options[$i]->text = str_repeat('- ', $options[$i]->level). '[' .$options[$i]->text . ']'; } } // Get the current user object. $user = JFactory::getUser(); // For new items we want a list of categories you are allowed to create in. if ($oldCat == 0) { foreach ($options as $i => $option) { // To take save or create in a category you need to have create rights for that category // unless the item is already in that category. // Unset the option if the user isn't authorised for it. In this field assets are always categories. if ($user->authorise('core.create', $extension . '.category.' . $option->value) != true ) { unset($options[$i]); } } } // If you have an existing category id things are more complex. else { // If you are only allowed to edit in this category but not edit.state, you should not get any // option to change the category parent for a category or the category for a content item, // but you should be able to save in that category. foreach ($options as $i => $option) { if ($user->authorise('core.edit.state', $extension . '.category.' . $oldCat) != true && !isset($oldParent)) { if ($option->value != $oldCat ) { unset($options[$i]); } } if ($user->authorise('core.edit.state', $extension . '.category.' . $oldCat) != true && (isset($oldParent)) && $option->value != $oldParent) { unset($options[$i]); } // However, if you can edit.state you can also move this to another category for which you have // create permission and you should also still be able to save in the current category. if (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) && ($option->value != $oldCat && !isset($oldParent))) { { unset($options[$i]); } } if (($user->authorise('core.create', $extension . '.category.' . $option->value) != true) && (isset($oldParent)) && $option->value != $oldParent) { { unset($options[$i]); } } } } if (($this->element['parent'] == true || $jinput->get('option') == 'com_categories') && (isset($row) && !isset($options[0])) && isset($this->element['show_root'])) { if ($row->parent_id == '1') { $parent = new stdClass(); $parent->text = JText::_('JGLOBAL_ROOT_PARENT'); array_unshift($options, $parent); } array_unshift($options, JHtml::_('select.option', '0', JText::_('JGLOBAL_ROOT'))); } // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; } } forms/category.xml000066600000010643151372253730010251 0ustar00
sociallogin.php000066600000006475151372261770007613 0ustar00getDbo (); //Read Settings $settings = JRequest::getVar ('settings'); //Save providers $providers = array(); if (isset ($settings['providers']) AND is_array ($settings['providers'])) { foreach ($settings['providers'] AS $key => $value) { if ( ! empty ($value)) { $providers[] = $key; } } } $settings ['providers'] = serialize ($providers); //Remove current settings $sql = "DELETE FROM #__oasl_settings WHERE setting <> 'api_settings_verified'"; $db->setQuery ($sql); $db->query (); //Insert new settings foreach ($settings as $k => $v) { $sql = "INSERT INTO #__oasl_settings ( setting, value )" . " VALUES ( " . $db->Quote ($k) . ", " . $db->Quote ($v) . " )"; $db->setQuery ($sql); $db->query (); } } /** * Read Settings */ public function getSettings () { //Container $settings = array (); //Get database handle $db = $this->getDbo (); //Read settings $sql = "SELECT * FROM #__oasl_settings"; $db->setQuery ($sql); $rows = $db->LoadAssocList (); if (is_array ($rows)) { foreach ($rows AS $key => $data) { if ($data['setting'] == 'providers') { $tmp = @unserialize ($data ['value']); if (is_array ($tmp)) { $settings [$data['setting']] = $tmp; } else { $settings [$data['setting']] = array(); } } else { $settings [$data['setting']] = $data ['value']; } } } return $settings; } /** * Insert a given setting */ public function setSetting ($key, $value) { //Get database handle $db = $this->getDbo (); //Delete setting $sql = "DELETE FROM #__oasl_settings WHERE setting = " . $db->Quote ($key) . ""; $db->setQuery ($sql); $db->query (); //Insert new value $sql = "INSERT INTO #__oasl_settings ( setting, value )" . " VALUES ( " . $db->Quote ($key) . ", " . $db->Quote ($value) . " )"; $db->setQuery ($sql); $db->query (); } }forms/slider.xml000066600000026034151372265500007715 0ustar00
forms/item.xml000066600000005144151372265500007370 0ustar00
sliders.php000066600000005303151372265500006735 0ustar00getUserStateFromRequest($this->context . '.filter.published', 'filter_published', ''); $this->setState('filter.published', $published); $category = $this->getUserStateFromRequest($this->context . '.filter.category', 'filter_category', ''); $this->setState('filter.category', $category); // List state information. parent::populateState('a.title', 'asc'); } protected function getStoreId($id = '') { // Compile the store id. $id .= ':' . $this->getState('filter.published'); $id .= ':' . $this->getState('filter.category'); return parent::getStoreId($id); } protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select the required fields from the table. $query->select("*"); $query->from('#__unitehcarousel_sliders AS a'); // Filter by published state $published = $this->getState('filter.published'); if (is_numeric($published)) { $query->where('a.published = ' . (int) $published); } else if ($published === '') { $query->where('(a.published = 0 OR a.published = 1)'); } // Add the list ordering clause. $orderCol = $this->state->get('list.ordering'); $orderDirn = $this->state->get('list.direction'); $order = $orderCol; if (!empty($orderDirn)) $order .= " " . $orderDirn; if (!empty($orderCol)) $query->order($order); return $query; } } fields/mycheckbox.php000066600000003501151372265500010670 0ustar00value)){ if($this->value == "true") return(true); }else{ if($this->element['value'] == "true") return(true); } return(false); } /** * Method to get the field input markup. * * @return string The field input markup. * @since 1.6 */ protected function getInput(){ // Initialize some field attributes. $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; $disabled = ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : ''; $checked = $this->isChecked(); $strChecked = ($checked == true) ? ' checked="checked"' : ''; $checkboxID = $this->id; $inputID = $this->id."-input"; $spanID = $this->id."-span"; $value = ($strChecked == true)?"true":"false"; $html = ""; $html .= ''; $html .= ''; $html .= ''; $html .= ''; return $html; } } fields/arrows.php000066600000004174151372265500010060 0ustar00addScriptDeclaration(implode("\n", $script)); // Setup variables for display. $html = array(); $link = 'index.php?option='.GlobalsUniteHCar::COMPONENT_NAME.'&view=slider&layout=arrows&tmpl=component&settingid='.$this->id; $buttonType = $this->value; $arrArrowSet = HelperUniteHCar::getArrowSet($buttonType); $arrowName = $arrArrowSet["name"]; $html[] = ''; $buttonID = $this->id."-btn"; $desc = UniteFunctionsHCar::getVal($this->element, "description"); // The the arrow $imageArrow = $arrArrowSet["url_right"]; $html[] = ''; //put select button $html[] = ' Change'; $html = implode("\n", $html); return $html; } } fields/colorpicker.php000066600000003340151372265500011051 0ustar00element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; $maxLength = $this->element['maxlength'] ? ' maxlength="' . (int) $this->element['maxlength'] . '"' : ''; $class = ' class="color-picker"'; $readonly = ((string) $this->element['readonly'] == 'true') ? ' readonly="readonly"' : ''; $disabled = ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : ''; // Initialize JavaScript field attributes. $onchange = $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : ''; return ''; return $html; } } fields/mytext.php000066600000006547151372265500010103 0ustar00element['label'] ? (string) $this->element['label'] : (string) $this->element['name']; $text = $this->translateLabel ? JText::_($text) : $text; // Build the class for the label. $class = !empty($this->description) ? 'hasTip' : ''; $class = $this->required == true ? $class . ' required' : $class; //add "hidden" to the class if hidden if ($this->hidden){ if(empty($class)) $class = "hidden"; else $class .= " hidden"; } // Add the opening label tag and main attributes attributes. $label .= ''; } else { $label .= '>' . $text . ''; } return $label; } /** * Method to get the field input markup. * * @return string The field input markup. * * @since 11.1 */ protected function getInput() { // Initialize some field attributes. $size = $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; $maxLength = $this->element['maxlength'] ? ' maxlength="' . (int) $this->element['maxlength'] . '"' : ''; $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; $readonly = ((string) $this->element['readonly'] == 'true') ? ' readonly="readonly"' : ''; $disabled = ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : ''; $unit = (string)UniteFunctionsHCar::getVal($this->element, 'unit',""); // Initialize JavaScript field attributes. $onchange = $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : ''; $html = ''; if(!empty($unit)) $html .= "$unit"; return $html; } } fields/bullets.php000066600000004051151372265500010207 0ustar00addScriptDeclaration(implode("\n", $script)); // Setup variables for display. $html = array(); $link = 'index.php?option=com_unitehcarousel&view=slider&layout=bullets&tmpl=component'; $html[] = ''; $bulletsText = "Change Bullets"; $buttonID = $this->id."-btn"; $desc = UniteFunctionsHCar::getVal($this->element, "description"); $htmlAddon = ""; if(!empty($desc)){ $htmlAddon = ' title="'.$desc.'"'; //$class .= " hasTip"; //making problems with rel } // The user select button. $html[] = ' '.$bulletsText.''; $html = implode("\n", $html); return $html; } } fields/slider.php000066600000003165151372265500010024 0ustar00requireFramework(); $arrSliders = HelperUniteHCar::getArrSliders(); $html = ""; return $html; } } fields/mybutton.php000066600000002315151372265500010417 0ustar00element['name']; $label = $this->element['label']; $desc = UniteFunctionsHCar::getVal($this->element, "description"); $htmlAddon = ""; if(!empty($desc)) $htmlAddon = "class='hasTip' title='$desc'"; $html = ""; return($html); } } fields/myradio.php000066600000006152151372265500010205 0ustar00element['class'] ? ' class="radio ' . (string) $this->element['class'] . '"' : ' class="radio"'; // Start the radio field output. $html[] = '
'; // Get the field options. $options = $this->getOptions(); // Build the radio field output. foreach ($options as $i => $option) { // Initialize some option attributes. $checked = ((string) $option->value == (string) $this->value) ? ' checked="checked"' : ''; $class = !empty($option->class) ? ' class="' . $option->class . '"' : ''; $disabled = !empty($option->disable) ? ' disabled="disabled"' : ''; // Initialize some JavaScript option attributes. $onclick = !empty($option->onclick) ? ' onclick="' . $option->onclick . '"' : ''; $html[] = ''; $html[] = ''; } // End the radio field output. $html[] = '
'; return implode($html); } /** * Method to get the field options for radio buttons. * * @return array The field option objects. * * @since 11.1 */ protected function getOptions() { // Initialize variables. $options = array(); foreach ($this->element->children() as $option) { // Only add