0
votes

I am trying to add an Avatar photo to jommla profile by follwing this steps 1- my server options PHP Built On Windows NT ******* 6.1 build 7600 (Windows 7 Home Premium Edition) i586 Database Version 5.5.5-10.1.10-MariaDB Database Collation utf8_general_ci Database Connection Collation utf8mb4_general_ci PHP Version 5.6.19 Web Server Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.19 WebServer to PHP Interface apache2handler Joomla! Version Joomla! 3.5.1 Stable [ Unicorn ] 05-April-2016 22:45 GMT Joomla! Platform Version Joomla Platform 13.1.0 Stable [ Curiosity ] 24-Apr-2013 00:00 GMT User Agent Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36

2- Relevant PHP Settings

Safe Mode Off Open basedir None Display Errors Off Short Open Tags Off File Uploads On Magic Quotes Off Register Globals Off Output Buffering Off Session Save Path C:\xampp\tmp Session Auto Start 0 XML Enabled Yes Zlib Enabled Yes Native ZIP Enabled Yes Disabled Functions None Multibyte String (mbstring) Enabled Yes Iconv Available Yes Maximum Input Variables 1000

3- files and fields editing

I added the file upload field in the file in

joomla_path/plugins/user/profile/profile.xml

I added this filed to joomla user profile plugin in back-end in the head of form

<field name="register-require_avatar"
type="list"
description="PLG_USER_PROFILE_FIELD_AVATAR_DESC"
label="PLG_USER_PROFILE_FIELD_AVATAR_LABEL"
>
<option value="2">JOPTION_REQUIRED</option>
<option value="1">JOPTION_OPTIONAL</option>
<option value="0">JDISABLED</option>
</field>

I added the (multipart/form-data) to the form. I added the file upload field in the file in

joomla_path/plugins/user/profile/profiles/profile.xml I added this filed to joomla user profile plugin in back-end in the head of form

<field
            name="avatar"
            type="file"
            id="avatar"
            description="PLG_USER_PROFILE_FIELD_AVATAR_DESC"
            label="PLG_USER_PROFILE_FIELD_AVATAR_LABEL"
        />

In the file profile.php which is in the path: joomla_path/plugins/user/profile/profile.php

I added this code to create user avatar folder and the code to upload the image file (I added this code in "onUserBeforeSave" Function)

import joomla's filesystem classes
    jimport('joomla.filesystem.folder');
    // Get the user info
    $user = JFactory::getUser();
    //The right way to create user folder and avatar folder
    $path = JPATH_SITE . '/images/users/'. $user->id . '-' . $user->username . '/avatar';
    JFolder::create($path);

    jimport('joomla.filesystem.file');
    $file = JRequest::getVar('jform', null, 'files', 'array');
    if (isset($file) && $file['size']['profile']['avatar'] != '') {
        //Clean up filename to get rid of strange characters like spaces etc
        $filename = JFile::makeSafe($file['name']);

        //First check if the file has the right extension, we need jpg only
        if ($file['type']['profile']['avatar'] == 'image/jpeg' || $file['type']['profile']['avatar'] == 'image/png' || $file['type']['profile']['avatar'] == 'image/gif') {
            if ($file['type']['profile']['avatar'] == 'image/png') {

                $image = imagecreatefrompng($file['tmp_name']['profile']['avatar']);
                imagejpeg($image, $path . '/avatar' . $filename .'.jpg', 80);
                imagedestroy($image);
                $image = JUri::root() . '/images/users/'. $user->id . '-' . $user->username . '/avatar/' . $filename;
            } else if ($file['type']['profile']['avatar'] == 'image/jpeg') {
                $image = imagecreatefromjpeg($file['tmp_name']['profile']['avatar']);
                imagejpeg($image, $path . '/avatar' . $filename .'.jpg', 80);
                imagedestroy($image);
            } else if ($file['type']['profile']['avatar'] == 'image/gif') {
                $image = imagecreatefromgif($file['tmp_name']['profile']['avatar']);
                imagejpeg($image, $path . '/avatar' . $filename . '.jpg', 80);
                imagedestroy($image);
            }
        } else {
            //Redirect and notify user file is not right extension
            throw new Exception(JText::_('PLG_USER_FILE_TYPE_INVALID'));

        return false;
    }
    return true;
}

    /////////////////////////////////////////////////

****** the problem is that i cant render the field in database to save the avatar file path **** must know that i can create the users's avatar folder and i can upload the image file to this path but the problem is how to save the file image's path in database then i can call it in any page by linking to this path so how is the right way to do this ???

2

2 Answers

0
votes

You can create a function to insert image into database

function insertAvatar($userid, $filename, $ext){

// Get a db connection.
$db = JFactory::getDbo();
try {
// Create a new query object.
$query = $db->getQuery(true);

// Insert columns.
$columns = array('user_id', 'profile_key', 'profile_value', 'ordering');

// Insert values.
$values = array($userid,'profile.avatar', $filename.$ext, 1);

// Prepare the insert query.
$query
    ->insert($db->quoteName('#__user_profiles'))
    ->columns($db->quoteName($columns))
    ->values(implode(',', $values));

$db->setQuery($query);
return $db->execute();
}
catch (Exception $e){
    return $e->getMessage();
}
}

Call the function at the appropriate place

if ($file['type']['profile']['avatar'] == 'image/png') {
   $this->insertAvatar($user->id, $filename, 'png');

Similarly for rest of the three types i.e "jpg" and "gif" use

$this->insertAvatar($user->id, $filename, 'jpg');

and

$this->insertAvatar($user->id, $filename, 'gif');

. you call other profile params the same way you can call image filename.

0
votes

This is the function that you created for me

function insertAvatar($userid, $filename, $ext){

    // Get a db connection.
    $db = JFactory::getDbo();
    try {
        // Create a new query object.
        $query = $db->getQuery(true);

        // Insert columns.
        $columns = array('user_id', 'profile_key', 'profile_value', 'ordering');

        // Insert values.
        $values = array($userid,'profile.avatar', $filename.$ext, 1);

        // Prepare the insert query.
        $query
            ->insert($db->quoteName('#__user_profiles'))
            ->columns($db->quoteName($columns))
            ->values(implode(',', $values));

        $db->setQuery($query);
        return $db->execute();
    }
    catch (Exception $e){
        return $e->getMessage();
    }
}

and this is the function (onUserBeforeSave) where i put my code

public function onUserBeforeSave($user, $isnew, $data)
{
    /////////////////////////////////////////////////////

    // import joomla's filesystem classes
    jimport('joomla.filesystem.folder');
    // Get the user info
    $user = JFactory::getUser();
    //The right way to create user folder and avatar folder
    $path = JPATH_SITE . '/images/users/'. $user->id . '-' . $user->username . '/avatar/';
    JFolder::create($path);

    jimport('joomla.filesystem.file');
    $file = JRequest::getVar('jform', null, 'files', 'array');
    if (isset($file) && $file['size']['profile']['avatar'] != 0) {
        //Clean up filename to get rid of strange characters like spaces etc
        $filename = JFile::makeSafe($file['name']);

        //First check if the file has the right extension, we need jpg only
        if ($file['type']['profile']['avatar'] == 'image/jpeg' || $file['type']['profile']['avatar'] == 'image/png' || $file['type']['profile']['avatar'] == 'image/gif') {
            if ($file['type']['profile']['avatar'] == 'image/png') {

                $image = imagecreatefrompng($file['tmp_name']['profile']['avatar']);
                imagejpeg($image, $path . $filename .'.jpg', 80);
                $this->insertAvatar($user->id, $filename, 'jpg');
                imagedestroy($image);

            } else if ($file['type']['profile']['avatar'] == 'image/jpeg') {
                $image = imagecreatefromjpeg($file['tmp_name']['profile']['avatar']);
                imagejpeg($image, $path . $filename .'.jpg', 80);
                $this->insertAvatar($user->id, $filename, 'jpg');
                imagedestroy($image);

            } else if ($file['type']['profile']['avatar'] == 'image/gif') {
                $image = imagecreatefromgif($file['tmp_name']['profile']['avatar']);
                imagejpeg($image, $path . $filename . '.jpg', 80);
                $this->insertAvatar($user->id, $filename, 'jpg');
                imagedestroy($image);
            }
        } else {
            //Redirect and notify user file is not right extension
            throw new Exception(JText::_('PLG_USER_FILE_TYPE_INVALID'));

            return false;
        }
        return true;
    }

    /////////////////////////////////////////////////

    // Check that the date is valid.
    if (!empty($data['profile']['dob']))
    {
        try
        {
            $date = new JDate($data['profile']['dob']);
            $this->date = $date->format('Y-m-d H:i:s');
        }
        catch (Exception $e)
        {
            // Throw an exception if date is not valid.
            throw new InvalidArgumentException(JText::_('PLG_USER_PROFILE_ERROR_INVALID_DOB'));
        }
        if (JDate::getInstance('now') < $date)
        {
            // Throw an exception if dob is greather than now.
            throw new InvalidArgumentException(JText::_('PLG_USER_PROFILE_ERROR_INVALID_DOB'));
        }
    }
    // Check that the tos is checked if required ie only in registration from frontend.
    $task       = JFactory::getApplication()->input->getCmd('task');
    $option     = JFactory::getApplication()->input->getCmd('option');
    $tosarticle = $this->params->get('register_tos_article');
    $tosenabled = ($this->params->get('register-require_tos', 0) == 2) ? true : false;
    if (($task == 'register') && ($tosenabled) && ($tosarticle) && ($option == 'com_user'))
    {
        // Check that the tos is checked.
        if ((!($data['profile']['tos'])))
        {
            throw new InvalidArgumentException(JText::_('PLG_USER_PROFILE_FIELD_TOS_DESC_SITE'));
        }
    }


    return true;
}

my code who is between the comments line like this /////////////////////////////////////