示例#1
0
 /**
  * Decorates the link object
  *
  * @since   1.3
  * @access  public
  * @param   string
  * @return  
  */
 public function decorate(&$link)
 {
     $db = JFactory::getDBO();
     $image = new mtImages($db);
     $image->load(array('link_id' => $link->link_id, 'ordering' => 1));
     require_once __DIR__ . '/models/listing.php';
     $model = new ListingModel('Listing');
     $link->link_image = $image->filename;
     $links = array(&$link);
     $model->decorate($links);
 }
示例#2
0
function savelisting($option)
{
    global $Itemid, $mtconf, $mainframe, $link_id;
    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');
    $database =& JFactory::getDBO();
    $my =& JFactory::getUser();
    require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'mfields.class.php';
    require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'tools.mtree.php';
    $raw_filenames = array();
    # Get cat_id / remove_image / link_image
    $cat_id = JRequest::getInt('cat_id', 0);
    $other_cats = explode(',', JRequest::getString('other_cats', null, 'post'));
    JArrayHelper::toInteger($other_cats);
    if (isset($other_cats) && empty($other_cats[0])) {
        $other_cats = array();
    }
    # Check if any malicious user is trying to submit link
    if ($mtconf->get('user_addlisting') == 1 && $my->id < 1 && $link_id == 0 || $mtconf->get('user_addlisting') == -1 && $link_id == 0 || $mtconf->get('user_allowmodify') == 0 && $link_id > 0) {
        echo _NOT_EXIST;
    } else {
        # Allowed
        $row = new mtLinks($database);
        $post = JRequest::get('post');
        if (!@$row->bind($post)) {
            echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
            exit;
        }
        $isNew = $row->link_id < 1 ? 1 : 0;
        # Assignment for new record
        if ($isNew) {
            $jdate = JFactory::getDate();
            $row->link_created = $jdate->toMySQL();
            $row->publish_up = $jdate->toMySQL();
            $row->ordering = 999;
            // Set an expire date for listing if enabled in configuration
            if ($mtconf->get('days_to_expire') > 0) {
                $jdate->setOffset(intval($mtconf->get('days_to_expire')) * 24);
                $row->publish_down = $jdate->toMySQL(true);
                $jdate->setOffset(intval($mtconf->get('days_to_expire')) * -24);
            }
            if ($my->id > 0) {
                $row->user_id = $my->id;
            } else {
                $database->setQuery('SELECT id FROM #__users WHERE usertype = \'Super Administrator\' LIMIT 1');
                $row->user_id = $database->loadResult();
            }
            if (empty($row->alias)) {
                $row->alias = JFilterOutput::stringURLSafe($row->link_name);
            }
            // Approval for adding listing
            if ($mtconf->get('needapproval_addlisting')) {
                $row->link_approved = '0';
            } else {
                $row->link_approved = 1;
                $row->link_published = 1;
                $row->updateLinkCount(1);
                $cache =& JFactory::getCache('com_mtree');
                $cache->clean();
            }
            # Modification to existing record
        } else {
            # Validate that this user is the rightful owner
            $database->setQuery("SELECT user_id FROM #__mt_links WHERE link_id = '" . $row->link_id . "'");
            $user_id = $database->loadResult();
            if ($user_id != $my->id) {
                echo _NOT_EXIST;
            } else {
                // Get the name of the old photo and last modified date
                $sql = "SELECT link_id, link_modified, link_created FROM #__mt_links WHERE link_id='" . $row->link_id . "'";
                $database->setQuery($sql);
                $old = $database->loadObject();
                // Retrive last modified date
                $old_modified = $old->link_modified;
                $link_created = $old->link_created;
                // $row->link_published = 1;
                $row->user_id = $my->id;
                // Get other info from original listing
                // $database->setQuery( "SELECT link_name, link_desc, link_hits, link_votes, link_rating, link_featured, link_created, link_visited, ordering, publish_down, publish_up, attribs, internal_notes, link_published, link_approved FROM #__mt_links WHERE link_id = '$row->link_id'" );
                $database->setQuery("SELECT * FROM #__mt_links WHERE link_id = '{$row->link_id}'");
                $original = $database->loadObject();
                $original_link_id = $row->link_id;
                $row->link_modified = $row->getLinkModified($original_link_id, $post);
                foreach ($original as $k => $v) {
                    if (in_array($k, array('link_hits', 'link_votes', 'link_rating', 'link_featured', 'link_created', 'link_visited', 'ordering', 'publish_down', 'publish_up', 'attribs', 'internal_notes', 'link_published', 'link_approved'))) {
                        $row->{$k} = $v;
                    }
                }
                if (!isset($row->metadesc) && isset($original->metadesc) && !empty($original->metadesc)) {
                    $row->metadesc = $original->metadesc;
                }
                if (!isset($row->metakey) && isset($original->metakey) && !empty($original->metakey)) {
                    $row->metakey = $original->metakey;
                }
                // Remove any listing that is waiting for approval for this listing
                $database->setQuery('SELECT link_id FROM #__mt_links WHERE link_approved = \'' . -1 * $row->link_id . '\' LIMIT 1');
                $tmp_pending_link_id = $database->loadResult();
                if ($tmp_pending_link_id > 0) {
                    $database->setQuery('SELECT CONCAT(' . $database->quote(JPATH_SITE . $mtconf->get('relative_path_to_attachments')) . ',raw_filename) FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($tmp_pending_link_id));
                    $raw_filenames = array_merge($raw_filenames, $database->loadResultArray());
                    $database->setQuery("DELETE FROM #__mt_cfvalues WHERE link_id = '" . $tmp_pending_link_id . "'");
                    $database->query();
                    $database->setQuery("DELETE FROM #__mt_cfvalues_att WHERE link_id = '" . $tmp_pending_link_id . "'");
                    $database->query();
                    $database->setQuery("DELETE FROM #__mt_links WHERE link_id = '" . $tmp_pending_link_id . "' LIMIT 1");
                    $database->query();
                    $database->setQuery("DELETE FROM #__mt_cl WHERE link_id = '" . $tmp_pending_link_id . "'");
                    $database->query();
                    $database->setQuery("SELECT filename FROM #__mt_images WHERE link_id = '" . $tmp_pending_link_id . "'");
                    $tmp_pending_images = $database->loadResultArray();
                    if (count($tmp_pending_images)) {
                        foreach ($tmp_pending_images as $tmp_pending_image) {
                            unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $tmp_pending_image);
                            unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $tmp_pending_image);
                            unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $tmp_pending_image);
                        }
                    }
                    $database->setQuery("DELETE FROM #__mt_images WHERE link_id = '" . $tmp_pending_link_id . "'");
                    $database->query();
                }
                // Approval for modify listing
                if ($original->link_published && $original->link_approved) {
                    if ($mtconf->get('needapproval_modifylisting')) {
                        $row->link_approved = -1 * $row->link_id;
                        $row->link_id = null;
                    } else {
                        $row->link_approved = 1;
                        $cache =& JFactory::getCache('com_mtree');
                        $cache->clean();
                        // Get old state (approved, published)
                        $database->setQuery("SELECT cat_id FROM #__mt_cl AS cl WHERE link_id ='" . $row->link_id . "' AND main = 1 LIMIT 1");
                        $old_state = $database->loadObject();
                        if ($row->cat_id != $old_state->cat_id) {
                            $row->updateLinkCount(1);
                            $row->updateLinkCount(-1, $old_state->cat_id);
                        }
                    }
                }
            }
        }
        // End of $isNew
        # Load field type
        $database->setQuery('SELECT cf_id, field_type, hidden, published FROM #__mt_customfields');
        $fieldtype = $database->loadObjectList('cf_id');
        $hidden_cfs = array();
        foreach ($fieldtype as $ft) {
            if ($ft->hidden && $ft->published) {
                $hidden_cfs[] = $ft->cf_id;
            }
        }
        # Load original custom field values, for use in mosetstree plugins
        $sql = "SELECT cf_id, value FROM #__mt_cfvalues WHERE link_id='" . $row->link_id . "' AND attachment <= 0";
        if (!empty($hidden_cfs)) {
            $sql .= " AND cf_id NOT IN (" . implode(',', $hidden_cfs) . ")";
        }
        $database->setQuery($sql);
        $original_cfs = $database->loadAssocList('cf_id');
        if (!empty($original_cfs)) {
            foreach ($original_cfs as $key_cf_id => $value) {
                $original_cfs[$key_cf_id] = $value['value'];
            }
        }
        # Erase Previous Records, make way for the new data
        $sql = "DELETE FROM #__mt_cfvalues WHERE link_id='" . $row->link_id . "' AND attachment <= 0";
        if (!empty($hidden_cfs)) {
            $sql .= " AND cf_id NOT IN (" . implode(',', $hidden_cfs) . ")";
        }
        $database->setQuery($sql);
        if (!$database->query()) {
            echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
            exit;
        }
        if (!empty($fieldtype)) {
            $load_ft = array();
            foreach ($fieldtype as $ft) {
                if (!in_array($ft->field_type, $load_ft)) {
                    $load_ft[] = $ft->field_type;
                }
            }
            $database->setQuery('SELECT ft_class FROM #__mt_fieldtypes WHERE field_type IN (\'' . implode('\',\'', $load_ft) . '\')');
            $ft_classes = $database->loadResultArray();
            foreach ($ft_classes as $ft_class) {
                eval($ft_class);
            }
        }
        # Collect all active custom field's id
        $active_cfs = array();
        $additional_cfs = array();
        $core_params = array();
        foreach ($post as $k => $v) {
            $v = JRequest::getVar($k, '', 'post', '', 2);
            if (substr($k, 0, 2) == "cf" && (!is_array($v) && (!empty($v) || $v == '0') || is_array($v) && !empty($v[0]))) {
                if (strpos(substr($k, 2), '_') === false && is_numeric(substr($k, 2))) {
                    // This custom field uses only one input. ie: cf17, cf23, cf2
                    $active_cfs[intval(substr($k, 2))] = $v;
                    if (is_array($v) && array_key_exists(intval(substr($k, 2)), $original_cfs)) {
                        $original_cfs[intval(substr($k, 2))] = explode('|', $original_cfs[intval(substr($k, 2))]);
                    }
                } else {
                    // This custom field uses more than one input. The date field is an example of cf that uses this. ie: cf13_0, cf13_1, cf13_2
                    $ids = explode('_', substr($k, 2));
                    if (count($ids) == 2 && is_numeric($ids[0]) && is_numeric($ids[1])) {
                        $additional_cfs[intval($ids[0])][intval($ids[1])] = $v;
                    }
                }
            } elseif (substr($k, 0, 7) == 'keep_cf') {
                $cf_id = intval(substr($k, 7));
                $keep_att_ids[] = $cf_id;
                # Perform parseValue on Core Fields
            } elseif (substr($k, 0, 2) != "cf" && isset($row->{$k})) {
                if (strpos(strtolower($k), 'link_') === false) {
                    $core_field_type = 'core' . $k;
                } else {
                    $core_field_type = 'core' . str_replace('link_', '', $k);
                }
                $class = 'mFieldType_' . $core_field_type;
                if (class_exists($class)) {
                    if (empty($core_params)) {
                        $database->setQuery('SELECT field_type, params FROM #__mt_customfields WHERE iscore = 1');
                        $core_params = $database->loadObjectList('field_type');
                    }
                    $mFieldTypeObject = new $class(array('params' => $core_params[$core_field_type]->params));
                    $v = call_user_func(array(&$mFieldTypeObject, 'parseValue'), $v);
                    $row->{$k} = $v;
                }
            }
        }
        # OK. Store new or updated listing into database
        if (!$row->store()) {
            echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
            exit;
        } else {
            if (!$isNew && $row->link_id > 0) {
                // Find if there are any additional categories assigned to the listinig
                if ($original_link_id != $row->link_id) {
                    $database->setQuery('SELECT DISTINCT cat_id FROM #__mt_cl WHERE link_id = ' . $database->Quote($original_link_id) . ' and main=\'0\' ');
                    $tmp_cats = $database->loadResultArray();
                    if (!empty($tmp_cats)) {
                        foreach ($tmp_cats as $tmp_cat_id) {
                            $database->setQuery('INSERT INTO #__mt_cl (`link_id`,`cat_id`,`main`) VALUES(' . $database->Quote($row->link_id) . ',' . $database->Quote($tmp_cat_id) . ',\'0\')');
                            $database->query();
                        }
                    }
                    unset($tmp_cats);
                }
            }
        }
        # Update "Also appear in these categories" aka other categories
        if ($mtconf->get('allow_user_assign_more_than_one_category')) {
            $mtCL = new mtCL_main0($database);
            $mtCL->load($row->link_id);
            $mtCL->update($other_cats);
        }
        // $files_cfs is used to store attachment custom fields.
        // This will be used in the next foreach loop to
        // prevent it from storing it's value to #__mt_cfvalues
        // table
        $file_cfs = array();
        // $file_values is used to store parsed data through
        // mFieldType_* which will be done in the next foreach
        // loop
        $file_values = array();
        $files = JRequest::get('files');
        foreach ($files as $k => $v) {
            if (substr($k, 0, 2) == "cf" && is_numeric(substr($k, 2)) && $v['error'] == 0) {
                $active_cfs[intval(substr($k, 2))] = $v;
                $file_cfs[] = substr($k, 2);
            }
        }
        if (!empty($active_cfs)) {
            $database->setQuery('SELECT cf_id, params FROM #__mt_customfields WHERE iscore = 0 AND cf_id IN (\'' . implode('\',\'', array_keys($active_cfs)) . '\') LIMIT ' . count($active_cfs));
            $params = $database->loadObjectList('cf_id');
            foreach ($active_cfs as $cf_id => $v) {
                if (class_exists('mFieldType_' . $fieldtype[$cf_id]->field_type)) {
                    $class = 'mFieldType_' . $fieldtype[$cf_id]->field_type;
                } else {
                    $class = 'mFieldType';
                }
                # Perform parseValue on Custom Fields
                $mFieldTypeObject = new $class(array('id' => $cf_id, 'params' => $params[$cf_id]->params));
                if (array_key_exists($cf_id, $additional_cfs) && !empty($additional_cfs[$cf_id])) {
                    $arr_v = $additional_cfs[$cf_id];
                    array_unshift($arr_v, $v);
                    $v =& $mFieldTypeObject->parseValue($arr_v);
                    $active_cfs[$cf_id] = $v;
                } else {
                    $v =& $mFieldTypeObject->parseValue($v);
                }
                if (in_array($cf_id, $file_cfs)) {
                    $file_values[$cf_id] = $v;
                }
                if ((!empty($v) || $v == '0') && !in_array($cf_id, $file_cfs)) {
                    # -- Now add the row
                    $sql = 'INSERT INTO #__mt_cfvalues (`cf_id`, `link_id`, `value`)' . ' VALUES (' . $database->quote($cf_id) . ', ' . $database->quote($row->link_id) . ', ' . $database->quote(is_array($v) ? implode("|", $v) : $v) . ')';
                    $database->setQuery($sql);
                    if (!$database->query()) {
                        echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
                        exit;
                    }
                }
                unset($mFieldTypeObject);
            }
            // End of foreach
        }
        # If this link is pending approval for modification, copy over hidden values
        if (!$isNew && $mtconf->get('needapproval_modifylisting') && !empty($hidden_cfs)) {
            $sql = 'INSERT INTO #__mt_cfvalues (`cf_id`, `link_id`, `value`)' . ' SELECT `cf_id`, \'' . $row->link_id . '\', `value` FROM #__mt_cfvalues WHERE link_id = ' . $original_link_id . ' AND cf_id IN (' . implode(',', $hidden_cfs) . ')';
            $database->setQuery($sql);
            $database->query();
        }
        # Remove all attachment except those that are kept
        if (isset($keep_att_ids) && !empty($keep_att_ids)) {
            $database->setQuery('SELECT CONCAT(' . $database->quote(JPATH_SITE . $mtconf->get('relative_path_to_attachments')) . ',raw_filename) FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id) . ' AND cf_id NOT IN (\'' . implode('\',\'', $keep_att_ids) . '\')');
            $raw_filenames = array_merge($raw_filenames, $database->loadResultArray());
            $database->setQuery('DELETE FROM #__mt_cfvalues_att WHERE link_id = \'' . $row->link_id . '\' AND cf_id NOT IN (\'' . implode('\',\'', $keep_att_ids) . '\')');
            $database->query();
            $database->setQuery('DELETE FROM #__mt_cfvalues WHERE link_id = \'' . $row->link_id . '\' AND cf_id NOT IN (\'' . implode('\',\'', $keep_att_ids) . '\') AND attachment > 0');
            $database->query();
        } else {
            $database->setQuery('SELECT CONCAT(' . $database->quote(JPATH_SITE . $mtconf->get('relative_path_to_attachments')) . ',raw_filename) FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id));
            $raw_filenames = array_merge($raw_filenames, $database->loadResultArray());
            $database->setQuery('DELETE FROM #__mt_cfvalues_att WHERE link_id = \'' . $row->link_id . '\'');
            $database->query();
            $database->setQuery('DELETE FROM #__mt_cfvalues WHERE link_id = \'' . $row->link_id . '\' AND attachment > 0');
            $database->query();
        }
        if (!$isNew && isset($keep_att_ids) && !empty($keep_att_ids) && $mtconf->get('needapproval_modifylisting') && $row->link_published == 1) {
            $database->setQuery("SELECT * FROM #__mt_cfvalues_att WHERE link_id = '" . $original_link_id . "' AND cf_id IN ('" . implode("','", $keep_att_ids) . "')");
            $listing_atts = $database->loadObjectList();
            foreach ($listing_atts as $listing_att) {
                $file_extension = pathinfo($listing_att->raw_filename);
                $file_extension = strtolower($file_extension['extension']);
                $database->setQuery('INSERT INTO #__mt_cfvalues_att (`link_id`,`cf_id`,`raw_filename`,`filename`,`filesize`,`extension`) ' . 'VALUES (' . $row->link_id . ', ' . $database->Quote($listing_att->cf_id) . ', ' . $database->Quote($listing_att->raw_filename) . ', ' . $database->Quote($listing_att->filename) . ', ' . $database->Quote($listing_att->filesize) . ', ' . $database->Quote($listing_att->extension) . ')');
                $database->query();
                $att_id = $database->insertid();
                $database->setQuery('UPDATE #__mt_cfvalues_att SET raw_filename = ' . $database->Quote($att_id . '.' . $file_extension) . ' WHERE att_id = ' . $database->Quote($att_id) . ' LIMIT 1');
                $database->query();
                copy($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_attachments') . $listing_att->raw_filename, $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_attachments') . $att_id . "." . $file_extension);
            }
            $database->setQuery('INSERT INTO #__mt_cfvalues (cf_id,link_id,value,attachment) ' . "\nSELECT cf_id,'" . $row->link_id . "',value,attachment " . "FROM #__mt_cfvalues " . "WHERE link_id = '" . $original_link_id . "' AND cf_id IN ('" . implode("','", $keep_att_ids) . "')");
            $database->query();
        }
        jimport('joomla.filesystem.file');
        foreach ($files as $k => $v) {
            if (substr($k, 0, 2) == "cf" && is_numeric(substr($k, 2)) && $v['error'] == 0) {
                $cf_id = intval(substr($k, 2));
                if (array_key_exists($cf_id, $file_values)) {
                    $file = $file_values[$cf_id];
                    if (!empty($file['data'])) {
                        $data = $file['data'];
                    } else {
                        $fp = fopen($v['tmp_name'], "r");
                        $data = fread($fp, $v['size']);
                        fclose($fp);
                    }
                } else {
                    $file = $v;
                    $fp = fopen($v['tmp_name'], "r");
                    $data = fread($fp, $v['size']);
                    fclose($fp);
                }
                $database->setQuery('SELECT CONCAT(' . $database->quote(JPATH_SITE . $mtconf->get('relative_path_to_attachments')) . ',raw_filename) FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id) . ' AND cf_id = ' . $database->quote($cf_id));
                $raw_filenames = array_merge($raw_filenames, $database->loadResultArray());
                $database->setQuery('DELETE FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id) . ' AND cf_id = ' . $database->quote($cf_id));
                $database->query();
                $database->setQuery('DELETE FROM #__mt_cfvalues WHERE cf_id = ' . $database->quote($cf_id) . ' AND link_id = ' . $database->quote($row->link_id) . ' AND attachment > 0');
                $database->query();
                $database->setQuery('INSERT INTO #__mt_cfvalues_att (link_id, cf_id, raw_filename, filename, filesize, extension) ' . ' VALUES(' . $database->quote($row->link_id) . ', ' . $database->quote($cf_id) . ', ' . $database->quote($file['name']) . ', ' . $database->quote($file['name']) . ', ' . $database->quote($file['size']) . ', ' . $database->quote($file['type']) . ')');
                if ($database->query() !== false) {
                    $att_id = $database->insertid();
                    $file_extension = strrchr($file['name'], '.');
                    if ($file_extension === false) {
                        $file_extension = '';
                    }
                    if (JFile::write(JPATH_SITE . $mtconf->get('relative_path_to_attachments') . $att_id . $file_extension, $data)) {
                        $database->setQuery('UPDATE #__mt_cfvalues_att SET raw_filename = ' . $database->quote($att_id . $file_extension) . ' WHERE att_id = ' . $database->quote($att_id) . ' LIMIT 1');
                        $database->query();
                        $sql = 'INSERT INTO #__mt_cfvalues (`cf_id`, `link_id`, `value`, `attachment`) ' . 'VALUES (' . $database->quote($cf_id) . ', ' . $database->quote($row->link_id) . ', ' . $database->quote($file['name']) . ',1)';
                        $database->setQuery($sql);
                        $database->query();
                    } else {
                        // Move failed, remove record from previously INSERTed row in #__mt_cfvalues_att
                        $database->setQuery('DELETE FROM #__mt_cfvalues_att WHERE att_id = ' . $database->quote($att_id) . ' LIMIT 1');
                        $database->query();
                    }
                }
            }
        }
        if (!empty($raw_filenames)) {
            JFile::delete($raw_filenames);
        }
        if ($mtconf->get('allow_imgupload') || !$mtconf->get('allow_imgupload') && $mtconf->get('needapproval_modifylisting')) {
            if ($mtconf->get('allow_imgupload')) {
                $keep_img_ids = JRequest::getVar('keep_img', null, 'post');
                JArrayHelper::toInteger($keep_img_ids, array());
                // If image upload is disabled, it will get the image IDs from database and make sure
                // the images are not lost after approval
            } else {
                $database->setQuery('SELECT img_id FROM #__mt_images WHERE link_id = ' . $database->quote($original_link_id));
                $keep_img_ids = $database->loadResultArray();
            }
            $redirectMsg = '';
            if (is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image')) && is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image')) && is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image'))) {
                // Duplicate listing images for approval
                if (!$isNew && !empty($keep_img_ids) && is_array($keep_img_ids) && $mtconf->get('needapproval_modifylisting')) {
                    foreach ($keep_img_ids as $keep_img_id) {
                        $database->setQuery('SELECT * FROM #__mt_images WHERE link_id = ' . $database->quote($original_link_id) . ' AND img_id = ' . $database->quote($keep_img_id) . ' LIMIT 1');
                        $original_image = $database->loadObject();
                        $file_extension = pathinfo($original_image->filename);
                        $file_extension = strtolower($file_extension['extension']);
                        $database->setQuery('INSERT INTO #__mt_images (link_id,filename,ordering) ' . "\n VALUES ('" . $row->link_id . "', '" . $original_image->filename . '_' . $row->link_id . "', '" . $original_image->ordering . "')");
                        $database->query();
                        $new_img_ids[$keep_img_id] = $database->insertid();
                        $database->setQuery("UPDATE #__mt_images SET filename = '" . $new_img_ids[$keep_img_id] . '_' . $row->link_id . '.' . $file_extension . "' WHERE img_id = '" . $new_img_ids[$keep_img_id] . "' LIMIT 1");
                        $database->query();
                        copy($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $original_image->filename, $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $new_img_ids[$keep_img_id] . '_' . $row->link_id . '.' . $file_extension);
                        copy($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $original_image->filename, $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $new_img_ids[$keep_img_id] . '_' . $row->link_id . '.' . $file_extension);
                        copy($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $original_image->filename, $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $new_img_ids[$keep_img_id] . '_' . $row->link_id . '.' . $file_extension);
                    }
                }
                # Remove all images except those that are kept when modification does not require approval
                $image_filenames = array();
                if (!$mtconf->get('needapproval_modifylisting')) {
                    if (isset($keep_img_ids) && !empty($keep_img_ids)) {
                        $database->setQuery('SELECT filename FROM #__mt_images WHERE link_id = \'' . $row->link_id . '\' AND img_id NOT IN (\'' . implode('\',\'', $keep_img_ids) . '\')');
                        $image_filenames = $database->loadResultArray();
                        $database->setQuery('DELETE FROM #__mt_images WHERE link_id = \'' . $row->link_id . '\' AND img_id NOT IN (\'' . implode('\',\'', $keep_img_ids) . '\')');
                        $database->query();
                    } else {
                        $database->setQuery('SELECT filename FROM #__mt_images WHERE link_id = \'' . $row->link_id . '\'');
                        $image_filenames = $database->loadResultArray();
                        $database->setQuery('DELETE FROM #__mt_images WHERE link_id = \'' . $row->link_id . '\'');
                        $database->query();
                    }
                }
                if (!empty($image_filenames)) {
                    foreach ($image_filenames as $image_filename) {
                        unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $image_filename);
                        unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $image_filename);
                        unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $image_filename);
                    }
                }
                $files_exceed_limit = false;
                if (isset($files['image'])) {
                    for ($i = 0; $i < count($files['image']['name']) && ($i < $mtconf->get('images_per_listing') - count($keep_img_ids) || $mtconf->get('images_per_listing') == '0'); $i++) {
                        if ($mtconf->get('image_maxsize') > 0 && $files['image']['size'][$i] > $mtconf->get('image_maxsize')) {
                            // Uploaded file exceed file limit
                            $files_exceed_limit = true;
                        } elseif (!empty($files['image']['name'][$i]) && $files['image']['error'][$i] == 0 && $files['image']['size'][$i] > 0) {
                            $file_extension = pathinfo($files['image']['name'][$i]);
                            $file_extension = strtolower($file_extension['extension']);
                            $mtImage = new mtImage();
                            $mtImage->setMethod($mtconf->get('resize_method'));
                            $mtImage->setQuality($mtconf->get('resize_quality'));
                            $mtImage->setSize($mtconf->get('resize_listing_size'));
                            $mtImage->setTmpFile($files['image']['tmp_name'][$i]);
                            $mtImage->setType($files['image']['type'][$i]);
                            $mtImage->setName($files['image']['name'][$i]);
                            $mtImage->setSquare($mtconf->get('squared_thumbnail'));
                            $mtImage->resize();
                            $mtImage->setDirectory($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image'));
                            $mtImage->saveToDirectory();
                            $mtImage->setSize($mtconf->get('resize_medium_listing_size'));
                            $mtImage->setSquare(false);
                            $mtImage->resize();
                            $mtImage->setDirectory($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image'));
                            $mtImage->saveToDirectory();
                            move_uploaded_file($files['image']['tmp_name'][$i], $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $files['image']['name'][$i]);
                            $database->setQuery('INSERT INTO #__mt_images (link_id, filename, ordering) ' . ' VALUES(' . $database->quote($row->link_id) . ', ' . $database->quote($files['image']['name'][$i]) . ', \'9999\')');
                            $database->query();
                            $img_id = $database->insertid();
                            rename($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $files['image']['name'][$i], $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $img_id . '.' . $file_extension);
                            rename($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $files['image']['name'][$i], $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $img_id . '.' . $file_extension);
                            rename($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $files['image']['name'][$i], $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $img_id . '.' . $file_extension);
                            $database->setQuery('UPDATE #__mt_images SET filename = ' . $database->quote($img_id . '.' . $file_extension) . ' WHERE img_id = ' . $database->quote($img_id));
                            $database->query();
                        }
                    }
                }
                if ($files_exceed_limit) {
                    if ($mtconf->get('image_maxsize') > 1048576) {
                        $image_upload_limit = round($mtconf->get('image_maxsize') / 1048576) . 'MB';
                    } else {
                        $image_upload_limit = round($mtconf->get('image_maxsize') / 1024) . 'KB';
                    }
                    $redirectMsg .= sprintf(JText::_('Image is not saved because it exceeded file size limit'), $image_upload_limit);
                }
                $img_sort_hash = JRequest::getVar('img_sort_hash', null, 'post');
                if (!empty($img_sort_hash)) {
                    $arr_img_sort_hashes = split("[&]*img\\[\\]=\\d*", $img_sort_hash);
                    $i = 1;
                    foreach ($arr_img_sort_hashes as $arr_img_sort_hash) {
                        if (!empty($arr_img_sort_hash) && $arr_img_sort_hash > 0) {
                            $sql = 'UPDATE #__mt_images SET ordering = ' . $database->quote($i) . ' WHERE img_id = ';
                            if (isset($new_img_ids) && !empty($new_img_ids)) {
                                $sql .= $database->quote(intval($new_img_ids[$arr_img_sort_hash]));
                            } else {
                                $sql .= $database->quote(intval($arr_img_sort_hash));
                            }
                            $sql .= ' LIMIT 1';
                            $database->setQuery($sql);
                            $database->query();
                            $i++;
                        }
                    }
                }
                $images = new mtImages($database);
                $images->reorder('link_id=' . $row->link_id);
            } else {
                if (isset($files['image'])) {
                    $redirectMsg .= JText::_('Image directories not writable');
                }
            }
        }
        # Send e-mail notification to user/admin upon adding a new listing
        // Get owner's email
        if ($my->id > 0) {
            $database->setQuery("SELECT email, name, username FROM #__users WHERE id = '" . $my->id . "' LIMIT 1");
            $author = $database->loadObject();
        } else {
            if (!empty($row->email)) {
                $author->email = $row->email;
            } else {
                $author->email = JText::_('Not specified');
            }
            $author->username = JText::_('None');
            $author->name = JText::_('Non registered user');
        }
        $uri =& JURI::getInstance();
        if ($isNew) {
            # To User
            if ($mtconf->get('notifyuser_newlisting') == 1 && ($my->id > 0 || !empty($author->email) && preg_match("/[\\w\\.\\-]+@\\w+[\\w\\.\\-]*?\\.\\w{1,4}/", $author->email) == true)) {
                if ($row->link_approved == 0) {
                    $subject = sprintf(JText::_('New listing email subject waiting approval'), $row->link_name);
                    $msg = JText::_('New listing email msg waiting approval');
                } else {
                    $subject = sprintf(JText::_('New listing email subject approved'), $row->link_name);
                    $msg = sprintf(JText::_('New listing email msg approved'), $row->link_name, $uri->toString(array('scheme', 'host', 'port')) . JRoute::_("index.php?option=com_mtree&task=viewlink&link_id={$row->link_id}&Itemid={$Itemid}"), $mtconf->getjconf('fromname'));
                }
                JUTility::sendMail($mtconf->getjconf('mailfrom'), $mtconf->getjconf('fromname'), $author->email, $subject, wordwrap($msg));
            }
            # To Admin
            if ($mtconf->get('notifyadmin_newlisting') == 1) {
                if ($row->link_approved == 0) {
                    $subject = sprintf(JText::_('New listing email subject waiting approval'), $row->link_name);
                    $msg = sprintf(JText::_('Admin new listing msg waiting approval'), $row->link_name, $row->link_name, $row->link_id, $author->name, $author->username, $author->email);
                } else {
                    $subject = sprintf(JText::_('New listing email subject approved'), $row->link_name);
                    $msg = sprintf(JText::_('Admin new listing msg approved'), $row->link_name, $uri->toString(array('scheme', 'host', 'port')) . JRoute::_("index.php?option=com_mtree&task=viewlink&link_id={$row->link_id}&Itemid={$Itemid}"), $row->link_name, $row->link_id, $author->name, $author->username, $author->email);
                }
                mosMailToAdmin($subject, $msg);
            }
        } elseif ($row->link_published == 1) {
            # To User
            if ($mtconf->get('notifyuser_modifylisting') == 1 && $my->id > 0) {
                if ($row->link_approved < 0) {
                    $subject = sprintf(JText::_('Modify listing email subject waiting approval'), $row->link_name);
                    $msg = sprintf(JText::_('Modify listing email msg waiting approval'), $row->link_name, $uri->toString(array('scheme', 'host', 'port')) . JRoute::_("index.php?option=com_mtree&task=viewlink&link_id={$old->link_id}&Itemid={$Itemid}"));
                } else {
                    $subject = sprintf(JText::_('Modify listing email subject approved'), $row->link_name);
                    $msg = sprintf(JText::_('Modify listing email msg approved'), $row->link_name, $uri->toString(array('scheme', 'host', 'port')) . JRoute::_("index.php?option=com_mtree&task=viewlink&link_id={$old->link_id}&Itemid={$Itemid}"), $mtconf->getjconf('fromname'));
                }
                JUTility::sendMail($mtconf->getjconf('mailfrom'), $mtconf->getjconf('fromname'), $author->email, $subject, wordwrap($msg));
            }
            # To Admin
            if ($mtconf->get('notifyadmin_modifylisting') == 1) {
                $diff_desc = diff_main($original->link_desc, $row->link_desc, true);
                diff_cleanup_semantic($diff_desc);
                $diff_desc = diff_prettyhtml($diff_desc);
                $msg = "<style type=\"text/css\">\n";
                $msg .= "ins{text-decoration:underline}\n";
                $msg .= "del{text-decoration:line-through}\n";
                $msg .= "</style>";
                if ($row->link_approved < 0) {
                    $subject = sprintf(JText::_('Modify listing email subject waiting approval'), $row->link_name);
                    $msg .= nl2br(sprintf(JText::_('Admin modify listing msg waiting approval'), $row->link_name, $uri->toString(array('scheme', 'host', 'port')) . JRoute::_("index.php?option=com_mtree&task=viewlink&link_id={$old->link_id}&Itemid={$Itemid}"), $row->link_name, $row->link_id, $author->name, $author->username, $author->email, $diff_desc));
                } else {
                    $subject = sprintf(JText::_('Modify listing email subject approved'), $row->link_name);
                    $msg .= nl2br(sprintf(JText::_('Admin modify listing msg approved'), $row->link_name, $uri->toString(array('scheme', 'host', 'port')) . JRoute::_("index.php?option=com_mtree&task=viewlink&link_id={$old->link_id}&Itemid={$Itemid}"), $row->link_name, $row->link_id, $author->name, $author->username, $author->email, $diff_desc));
                }
                mosMailToAdmin($subject, $msg, 1);
            }
        }
        // Fire mosetstree onAfterModifyListing plugin
        $dispatcher =& JDispatcher::getInstance();
        JPluginHelper::importPlugin('mosetstree');
        $dispatcher->trigger('onAfterModifyListing', array((array) $original, $original_cfs, (array) $row, $active_cfs, $old->link_id, $cat_id));
        if (isset($original) && $original->link_published && $original->link_approved) {
            if ($isNew && $mtconf->get('needapproval_addlisting')) {
                $redirect_url = "index.php?option={$option}&task=listcats&cat_id={$cat_id}&Itemid={$Itemid}";
            } elseif (!$isNew && $mtconf->get('needapproval_modifylisting')) {
                $redirect_url = "index.php?option={$option}&task=viewlink&link_id={$old->link_id}&Itemid={$Itemid}";
            } else {
                $redirect_url = "index.php?option={$option}&task=viewlink&link_id={$row->link_id}&Itemid={$Itemid}";
            }
        } else {
            $redirect_url = "index.php?option={$option}&task=mypage&Itemid={$Itemid}";
        }
        $mainframe->redirect(JRoute::_($redirect_url), ($isNew ? $mtconf->get('needapproval_addlisting') ? JText::_('Listing will be reviewed') : JText::_('Listing have been added') : ($mtconf->get('needapproval_modifylisting') ? JText::_('Listing modification will be reviewed') : JText::_('Listing have been updated'))) . (!empty($redirectMsg) ? '<br /> ' . $redirectMsg : ''));
    }
}
示例#3
0
function savelink($option, $post = null)
{
    global $mtconf, $mainframe;
    $database =& JFactory::getDBO();
    $my =& JFactory::getUser();
    $config =& JFactory::getConfig();
    $nullDate = $database->getNullDate();
    $stored = false;
    $row = new mtLinks($database);
    if (is_null($post)) {
        $post = JRequest::get('post');
    }
    if (!$row->bind($post)) {
        echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
        exit;
    }
    $original_link_id = (int) $post['original_link_id'];
    $cat_id = (int) $post['cat_id'];
    $row->cat_id = $cat_id;
    $other_cats = explode(',', $post['other_cats']);
    $tzoffset = $config->getValue('config.offset');
    $publishing = $post['publishing'];
    $row->bind($publishing);
    # Is this a new listing?
    $new_link = false;
    $old_image = '';
    // Yes, new listing
    if ($row->link_id == 0) {
        $new_link = true;
        if ($row->link_created && strlen(trim($row->link_created)) <= 10) {
            $row->link_created .= ' 00:00:00';
        }
        $date =& JFactory::getDate($row->link_created, $tzoffset);
        $row->link_created = $date->toMySQL();
        // No, this listing has been saved to the database
        // 1) Submission from visitor
        // 2) Modification request from listing owner
    } else {
        $row->link_modified = $row->getLinkModified(empty($original_link_id) ? $row->link_id : $original_link_id, $post);
        # Let's check if this link is on "pending approval" from an existing listing
        $database->setQuery("SELECT link_approved FROM #__mt_links WHERE link_id = {$row->link_id} LIMIT 1");
        $thislink = $database->loadObject();
        // 1: approved; 0:unapproved/new listing; <-1: pending approval for update
        $link_approved = $thislink->link_approved;
        if ($link_approved < 0 && $row->link_approved == 0) {
            $row->link_approved = $link_approved;
        }
    }
    // Append time if not added to publish date
    if (strlen(trim($row->publish_up)) <= 10) {
        $row->publish_up .= ' 00:00:00';
    }
    $date =& JFactory::getDate($row->publish_up, $tzoffset);
    $row->publish_up = $date->toMySQL();
    // Handle never unpublish date
    if (trim($row->publish_down) == JText::_('Never') || trim($row->publish_down) == '') {
        $row->publish_down = $nullDate;
    } else {
        if (strlen(trim($row->publish_down)) <= 10) {
            $row->publish_down .= ' 00:00:00';
        }
        $date =& JFactory::getDate($row->publish_down, $tzoffset);
        $row->publish_down = $date->toMySQL();
    }
    $notes = $post['notes'];
    $row->bind($notes);
    # Lookup owner's userid. Return error if does not exists
    if ($publishing['owner'] == '') {
        // If owner field is left blank, assign the link to the current user
        $row->user_id = $my->id;
    } else {
        $database->setQuery('SELECT id FROM #__users WHERE username = '******'owner']));
        $owner_id = $database->loadResult();
        if ($owner_id > 0) {
            $row->user_id = $owner_id;
        } else {
            echo "<script> alert('" . JText::_('Invalid owner select again') . "'); window.history.go(-1); </script>\n";
            exit;
        }
    }
    # Listing alias
    if (empty($row->alias)) {
        $row->alias = JFilterOutput::stringURLSafe($row->link_name);
    }
    # Save parameters
    $params = $post['params'];
    if (is_array($params)) {
        $attribs = array();
        foreach ($params as $k => $v) {
            $attribs[] = "{$k}={$v}";
        }
        $row->attribs = implode("\n", $attribs);
    }
    # Publish the listing
    if ($row->link_published && $row->link_id > 0) {
        $row->publishLink(1);
    }
    # Approve listing and send e-mail notification to the owner and admin
    if ($row->link_approved == 1 && $row->link_id > 0) {
        # Get this actual link_approved value from DB
        $database->setQuery('SELECT link_approved FROM #__mt_links WHERE link_id = ' . $database->quote($row->link_id));
        $link_approved = $database->loadResult();
        # This is a modification to the existing listing
        if ($link_approved <= 0) {
            $row->updateLinkCount(1);
            $row->approveLink();
            // $stored = true;
        }
    }
    # Update the Link Counts for all cat_parent(s)
    if ($new_link) {
        $row->updateLinkCount(1);
    } else {
        // Get old state (approved, published)
        $database->setQuery('SELECT link_approved, link_published, cl.cat_id FROM (#__mt_links AS l, #__mt_cl AS cl) WHERE l.link_id = cl.link_id AND l.link_id = ' . $database->quote($row->link_id) . ' LIMIT 1');
        $old_state = $database->loadObject();
        // From approved & published -to-> unapproved/unpublished
        if ($old_state->link_approved == 1 && $old_state->link_published == 1) {
            if ($row->link_published == 0 || $row->link_approved == 0) {
                $row->updateLinkCount(-1);
            }
            // From unpublished/unapproved -to-> Published & Approved
        } elseif ($row->link_published == 1 && $row->link_approved == 1) {
            $row->updateLinkCount(1);
        }
        // Update link count if changing to a new category
        if ($old_state->cat_id != $cat_id && $old_state->link_approved != 0) {
            $oldrow = new mtLinks($database);
            $oldrow->cat_id = $old_state->cat_id;
            $oldrow->updateLinkCount(-1);
            $newrow = new mtLinks($database);
            $newrow->cat_id = $cat_id;
            $newrow->updateLinkCount(1);
        }
    }
    # Erase Previous Records, make way for the new data
    $sql = 'DELETE FROM #__mt_cfvalues WHERE link_id= ' . $database->quote($row->link_id) . ' AND attachment <= 0';
    $database->setQuery($sql);
    if (!$database->query()) {
        echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        exit;
    }
    # Load field type
    $database->setQuery('SELECT cf_id, field_type FROM #__mt_customfields');
    $fieldtype = $database->loadObjectList('cf_id');
    if (count($fieldtype) > 0) {
        $load_ft = array();
        foreach ($fieldtype as $ft) {
            if (!in_array($ft->field_type, $load_ft)) {
                $load_ft[] = $ft->field_type;
            }
        }
        $database->setQuery('SELECT ft_class FROM #__mt_fieldtypes WHERE field_type IN (\'' . implode('\',\'', $load_ft) . '\')');
        $ft_classes = $database->loadResultArray();
        foreach ($ft_classes as $ft_class) {
            eval($ft_class);
        }
    }
    # Collect all active custom field's id
    $active_cfs = array();
    $additional_cfs = array();
    $core_params = array();
    foreach ($post as $k => $v) {
        $v = JRequest::getVar($k, '', 'post', '', 2);
        if (substr($k, 0, 2) == "cf" && (!is_array($v) && (!empty($v) || $v == '0') || is_array($v) && !empty($v[0]))) {
            if (strpos(substr($k, 2), '_') === false && is_numeric(substr($k, 2))) {
                // This custom field uses only one input. ie: cf17, cf23, cf2
                $active_cfs[intval(substr($k, 2))] = $v;
            } else {
                // This custom field uses more than one input. The date field is an example of cf that uses this. ie: cf13_0, cf13_1, cf13_2
                $ids = explode('_', substr($k, 2));
                if (count($ids) == 2 && is_numeric($ids[0]) && is_numeric($ids[1])) {
                    $additional_cfs[intval($ids[0])][intval($ids[1])] = $v;
                }
            }
        } elseif (substr($k, 0, 7) == 'keep_cf') {
            $cf_id = intval(substr($k, 7));
            $keep_att_ids[] = $cf_id;
            # Perform parseValue on Core Fields
        } elseif (substr($k, 0, 2) != "cf" && isset($row->{$k})) {
            if (strpos(strtolower($k), 'link_') === false) {
                $core_field_type = 'core' . $k;
            } else {
                $core_field_type = 'core' . str_replace('link_', '', $k);
            }
            $class = 'mFieldType_' . $core_field_type;
            if (class_exists($class)) {
                if (empty($core_params)) {
                    $database->setQuery('SELECT field_type, params FROM #__mt_customfields WHERE iscore = 1');
                    $core_params = $database->loadObjectList('field_type');
                }
                $mFieldTypeObject = new $class(array('params' => $core_params[$core_field_type]->params));
                $v = call_user_func(array(&$mFieldTypeObject, 'parseValue'), $v);
                $row->{$k} = $v;
            }
        }
    }
    if (!$stored) {
        # Save core values to database
        if (!$row->store()) {
            echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
            exit;
        } else {
            # If this is a newlink, rename the photo to listingID_photoName.jpg
            if ($new_link) {
                // Get last inserted listing ID
                $mysql_last_insert_cl_id = $database->insertid();
                $database->setQuery('SELECT link_id FROM #__mt_cl WHERE cl_id = ' . $database->quote($mysql_last_insert_cl_id));
                $mysql_last_insert_id = $database->loadResult();
            }
        }
    }
    // $files_cfs is used to store attachment custom fields.
    // This will be used in the next foreach loop to
    // prevent it from storing it's value to #__mt_cfvalues
    // table
    $file_cfs = array();
    // $file_values is used to store parsed data through
    // mFieldType_* which will be done in the next foreach
    // loop
    $file_values = array();
    $files = JRequest::get('files');
    foreach ($files as $k => $v) {
        if (substr($k, 0, 2) == "cf" && is_numeric(substr($k, 2)) && $v['error'] == 0) {
            $active_cfs[intval(substr($k, 2))] = $v;
            $file_cfs[] = intval(substr($k, 2));
        }
    }
    if (count($active_cfs) > 0) {
        $database->setQuery('SELECT cf_id, params FROM #__mt_customfields WHERE iscore = 0 AND cf_id IN (\'' . implode('\',\'', array_keys($active_cfs)) . '\') LIMIT ' . count($active_cfs));
        $params = $database->loadObjectList('cf_id');
        foreach ($active_cfs as $cf_id => $v) {
            if (class_exists('mFieldType_' . $fieldtype[$cf_id]->field_type)) {
                $class = 'mFieldType_' . $fieldtype[$cf_id]->field_type;
            } else {
                $class = 'mFieldType';
            }
            # Perform parseValue on Custom Fields
            $mFieldTypeObject = new $class(array('id' => $cf_id, 'params' => $params[$cf_id]->params));
            if (array_key_exists($cf_id, $additional_cfs) && count($additional_cfs[$cf_id]) > 0) {
                $arr_v = $additional_cfs[$cf_id];
                array_unshift($arr_v, $v);
                $v =& $mFieldTypeObject->parseValue($arr_v);
            } else {
                $v =& $mFieldTypeObject->parseValue($v);
            }
            if (in_array($cf_id, $file_cfs)) {
                $file_values[$cf_id] = $v;
            }
            if ((!empty($v) || $v == '0') && !in_array($cf_id, $file_cfs)) {
                # -- Now add the row
                $sql = 'INSERT INTO #__mt_cfvalues (`cf_id`, `link_id`, `value`)' . "\nVALUES (" . $database->quote($cf_id) . ', ' . $database->quote($row->link_id) . ', ' . $database->quote(is_array($v) ? implode('|', $v) : $v) . ')';
                $database->setQuery($sql);
                if (!$database->query()) {
                    echo "<script> alert('" . $database->getErrorMsg() . "'); window.history.go(-1); </script>\n";
                    exit;
                }
            }
            unset($mFieldTypeObject);
        }
        // End of foreach
    }
    # Remove all attachment except those that are kept
    $raw_filenames = array();
    if (isset($keep_att_ids) && count($keep_att_ids) > 0) {
        $database->setQuery('SELECT CONCAT(' . $database->quote(JPATH_SITE . $mtconf->get('relative_path_to_attachments')) . ',raw_filename) FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id) . ' AND cf_id NOT IN (\'' . implode('\',\'', $keep_att_ids) . '\')');
        $raw_filenames = $database->loadResultArray();
        $database->setQuery('DELETE FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id) . ' AND cf_id NOT IN (\'' . implode('\',\'', $keep_att_ids) . '\')');
        $database->query();
        $database->setQuery('DELETE FROM #__mt_cfvalues WHERE link_id = ' . $database->quote($row->link_id) . ' AND cf_id NOT IN (\'' . implode('\',\'', $keep_att_ids) . '\') AND attachment > 0');
        $database->query();
    } else {
        $database->setQuery('SELECT CONCAT(' . $database->quote(JPATH_SITE . $mtconf->get('relative_path_to_attachments')) . ',raw_filename) FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id));
        $raw_filenames = $database->loadResultArray();
        $database->setQuery('DELETE FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id));
        $database->query();
        $database->setQuery('DELETE FROM #__mt_cfvalues WHERE link_id = ' . $database->quote($row->link_id) . ' AND attachment > 0');
        $database->query();
    }
    jimport('joomla.filesystem.file');
    foreach ($files as $k => $v) {
        if (substr($k, 0, 2) == "cf" && is_numeric(substr($k, 2)) && $v['error'] == 0) {
            $cf_id = intval(substr($k, 2));
            if (array_key_exists($cf_id, $file_values)) {
                $file = $file_values[$cf_id];
                if (!empty($file['data'])) {
                    $data = $file['data'];
                } else {
                    $fp = fopen($v['tmp_name'], "r");
                    $data = fread($fp, $v['size']);
                    fclose($fp);
                }
            } else {
                $file = $v;
                $fp = fopen($v['tmp_name'], "r");
                $data = fread($fp, $v['size']);
                fclose($fp);
            }
            $database->setQuery('SELECT CONCAT(' . $database->quote(JPATH_SITE . $mtconf->get('relative_path_to_attachments')) . ',raw_filename) FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id) . ' AND cf_id = ' . $database->quote($cf_id));
            $raw_filenames = array_merge($raw_filenames, $database->loadResultArray());
            $database->setQuery('DELETE FROM #__mt_cfvalues_att WHERE link_id = ' . $database->quote($row->link_id) . ' AND cf_id = ' . $database->quote($cf_id));
            $database->query();
            $database->setQuery('DELETE FROM #__mt_cfvalues WHERE cf_id = ' . $database->quote($cf_id) . ' AND link_id = ' . $database->quote($row->link_id) . ' AND attachment > 0');
            $database->query();
            $database->setQuery('INSERT INTO #__mt_cfvalues_att (link_id, cf_id, raw_filename, filename, filesize, extension) ' . 'VALUES(' . $database->quote($row->link_id) . ', ' . $database->quote($cf_id) . ', ' . $database->quote($file['name']) . ', ' . $database->quote($file['name']) . ', ' . $database->quote($file['size']) . ', ' . $database->quote($file['type']) . ')');
            if ($database->query() !== false) {
                $att_id = $database->insertid();
                $file_extension = strrchr($file['name'], '.');
                if ($file_extension === false) {
                    $file_extension = '';
                }
                if (JFile::write(JPATH_SITE . $mtconf->get('relative_path_to_attachments') . $att_id . $file_extension, $data)) {
                    $database->setQuery('UPDATE #__mt_cfvalues_att SET raw_filename = ' . $database->quote($att_id . $file_extension) . ' WHERE att_id = ' . $database->quote($att_id) . ' LIMIT 1');
                    $database->query();
                    $sql = 'INSERT INTO #__mt_cfvalues (`cf_id`, `link_id`, `value`, `attachment`) ' . 'VALUES (' . $database->quote($cf_id) . ', ' . $database->quote($row->link_id) . ', ' . $database->quote($file['name']) . ',1)';
                    $database->setQuery($sql);
                    $database->query();
                } else {
                    // Move failed, remove record from previously INSERTed row in #__mt_cfvalues_att
                    $database->setQuery('DELETE FROM #__mt_cfvalues_att WHERE att_id = ' . $database->quote($att_id) . ' LIMIT 1');
                    $database->query();
                }
            }
        }
    }
    if (!empty($raw_filenames)) {
        JFile::delete($raw_filenames);
    }
    # Remove all images except those that are kept
    $msg = '';
    if (is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image')) && is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image')) && is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image'))) {
        if (isset($post['keep_img'])) {
            $keep_img_ids = $post['keep_img'];
            JArrayHelper::toInteger($keep_img_ids, array());
        }
        $image_filenames = array();
        if (isset($keep_img_ids) && count($keep_img_ids) > 0) {
            $database->setQuery('SELECT filename FROM #__mt_images WHERE link_id = ' . $database->quote($row->link_id) . ' AND img_id NOT IN (\'' . implode('\',\'', $keep_img_ids) . '\')');
            $image_filenames = $database->loadResultArray();
            $database->setQuery('DELETE FROM #__mt_images WHERE link_id = ' . $database->quote($row->link_id) . ' AND img_id NOT IN (\'' . implode('\',\'', $keep_img_ids) . '\')');
            $database->query();
        } else {
            $database->setQuery('SELECT filename FROM #__mt_images WHERE link_id = ' . $database->quote($row->link_id));
            $image_filenames = $database->loadResultArray();
            $database->setQuery('DELETE FROM #__mt_images WHERE link_id = ' . $database->quote($row->link_id));
            $database->query();
        }
        if (count($image_filenames)) {
            foreach ($image_filenames as $image_filename) {
                unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $image_filename);
                unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $image_filename);
                unlink($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $image_filename);
            }
        }
    }
    $images = new mtImages($database);
    if (isset($files['image'])) {
        if (!is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image')) || !is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image')) || !is_writable($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image'))) {
            $msg = JText::_('Image directories not writable');
        } else {
            for ($i = 0; $i < count($files['image']['name']); $i++) {
                if (!empty($files['image']['name'][$i]) && $files['image']['error'][$i] == 0 && $files['image']['size'][$i] > 0) {
                    $file_extension = pathinfo($files['image']['name'][$i]);
                    $file_extension = strtolower($file_extension['extension']);
                    $mtImage = new mtImage();
                    $mtImage->setMethod($mtconf->get('resize_method'));
                    $mtImage->setQuality($mtconf->get('resize_quality'));
                    $mtImage->setSize($mtconf->get('resize_listing_size'));
                    $mtImage->setTmpFile($files['image']['tmp_name'][$i]);
                    $mtImage->setType($files['image']['type'][$i]);
                    $mtImage->setName($files['image']['name'][$i]);
                    $mtImage->setSquare($mtconf->get('squared_thumbnail'));
                    $mtImage->resize();
                    $mtImage->setDirectory($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image'));
                    $mtImage->saveToDirectory();
                    $mtImage->setSize($mtconf->get('resize_medium_listing_size'));
                    $mtImage->setSquare(false);
                    $mtImage->resize();
                    $mtImage->setDirectory($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image'));
                    $mtImage->saveToDirectory();
                    move_uploaded_file($files['image']['tmp_name'][$i], JPath::clean($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $files['image']['name'][$i]));
                    $database->setQuery("INSERT INTO #__mt_images (link_id, filename, ordering) " . 'VALUES(' . $database->quote($row->link_id) . ', ' . $database->quote($files['image']['name'][$i]) . ', 9999)');
                    $database->query();
                    $img_id = intval($database->insertid());
                    $old_small_image_path = JPath::clean($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $files['image']['name'][$i]);
                    $old_medium_image_path = JPath::clean($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $files['image']['name'][$i]);
                    $old_original_image_path = JPath::clean($mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $files['image']['name'][$i]);
                    rename($old_small_image_path, $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_small_image') . $img_id . '.' . $file_extension);
                    rename($old_medium_image_path, $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_medium_image') . $img_id . '.' . $file_extension);
                    rename($old_original_image_path, $mtconf->getjconf('absolute_path') . $mtconf->get('relative_path_to_listing_original_image') . $img_id . '.' . $file_extension);
                    $database->setQuery('UPDATE #__mt_images SET filename = ' . $database->quote($img_id . '.' . $file_extension) . ' WHERE img_id = ' . $database->quote($img_id));
                    $database->query();
                }
            }
        }
    }
    $img_sort_hash = $post['img_sort_hash'];
    if (!empty($img_sort_hash)) {
        $arr_img_sort_hashes = split("[&]*img\\[\\]=\\d*", $img_sort_hash);
        $i = 1;
        foreach ($arr_img_sort_hashes as $arr_img_sort_hash) {
            if (!empty($arr_img_sort_hash) && $arr_img_sort_hash > 0) {
                $database->setQuery('UPDATE #__mt_images SET ordering = ' . $database->quote($i) . ' WHERE img_id = ' . $database->quote(intval($arr_img_sort_hash)) . ' LIMIT 1');
                $database->query();
                $i++;
            }
        }
    }
    $images->reorder('link_id=' . $row->link_id);
    # Update "Also appear in these categories" aka other categories
    $mtCL = new mtCL_main0($database);
    $mtCL->load($row->link_id);
    $mtCL->update($other_cats);
    $returntask = $post['returntask'];
    //*
    if ($returntask != '') {
        $mainframe->redirect("index2.php?option={$option}&task={$returntask}", $msg);
    } else {
        $task = JFilterInput::clean($post['task'], 'cmd');
        if ($task == "applylink") {
            $mainframe->redirect("index2.php?option={$option}&task=editlink&link_id={$row->link_id}", $msg);
        } else {
            $mainframe->redirect("index2.php?option={$option}&task=listcats&cat_id={$cat_id}", $msg);
        }
    }
    // */
}