Пример #1
0
/**
 * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
 * Sender name and email can be specified, if not specified
 * name and email of the platform admin are used
 *
 * @author Bert Vanderkimpen ICT&O UGent
 * @author Yannick Warnier <*****@*****.**>
 *
 * @param string    name of recipient
 * @param string    email of recipient
 * @param string    email subject
 * @param string    email body
 * @param string    sender name
 * @param string    sender e-mail
 * @param array     extra headers in form $headers = array($name => $value) to allow parsing
 * @param array     data file (path and filename)
 * @param array     data to attach a file (optional)
 * @param bool      True for attaching a embedded file inside content html (optional)
 * @return          returns true if mail was sent
 * @see             class.phpmailer.php
 */
function api_mail_html($recipient_name, $recipient_email, $subject, $message, $senderName = '', $senderEmail = '', $extra_headers = array(), $data_file = array(), $embedded_image = false, $additionalParameters = array())
{
    // Default values
    $notification = new Notification();
    $defaultEmail = $notification->getDefaultPlatformSenderEmail();
    $defaultName = $notification->getDefaultPlatformSenderName();
    // If the parameter is set don't use the admin.
    $senderName = !empty($senderName) ? $senderName : $defaultName;
    $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail;
    $link = isset($additionalParameters['link']) ? $additionalParameters['link'] : '';
    $swiftMessage = \Swift_Message::newInstance()->setSubject($subject)->setFrom($senderEmail, $senderName)->setTo($recipient_email, $recipient_name)->setBody(Container::getTemplating()->render('ChamiloCoreBundle:default/mail:mail.html.twig', array('content' => $message, 'link' => $link)), 'text/html');
    if (!empty($additionalParameters)) {
        $plugin = new AppPlugin();
        $smsPlugin = $plugin->getSMSPluginLibrary();
        if ($smsPlugin) {
            $smsPlugin->send($additionalParameters);
        }
    }
    Container::getMailer()->send($swiftMessage);
    return 1;
    global $platform_email;
    $mail = new PHPMailer();
    $mail->Mailer = $platform_email['SMTP_MAILER'];
    $mail->Host = $platform_email['SMTP_HOST'];
    $mail->Port = $platform_email['SMTP_PORT'];
    $mail->CharSet = $platform_email['SMTP_CHARSET'];
    // Stay far below SMTP protocol 980 chars limit.
    $mail->WordWrap = 200;
    if ($platform_email['SMTP_AUTH']) {
        $mail->SMTPAuth = 1;
        $mail->Username = $platform_email['SMTP_USER'];
        $mail->Password = $platform_email['SMTP_PASS'];
    }
    // 5 = low, 1 = high
    $mail->Priority = 3;
    $mail->SMTPKeepAlive = true;
    // Default values
    $notification = new Notification();
    $defaultEmail = $notification->getDefaultPlatformSenderEmail();
    $defaultName = $notification->getDefaultPlatformSenderName();
    // Error to admin.
    $mail->AddCustomHeader('Errors-To: ' . $defaultEmail);
    // If the parameter is set don't use the admin.
    $senderName = !empty($senderName) ? $senderName : $defaultName;
    $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail;
    // Reply to first
    if (isset($extra_headers['reply_to'])) {
        $mail->AddReplyTo($extra_headers['reply_to']['mail'], $extra_headers['reply_to']['name']);
        $mail->Sender = $extra_headers['reply_to']['mail'];
        unset($extra_headers['reply_to']);
    }
    //If the SMTP configuration only accept one sender
    if ($platform_email['SMTP_UNIQUE_SENDER']) {
        $senderName = $platform_email['SMTP_FROM_NAME'];
        $senderEmail = $platform_email['SMTP_FROM_EMAIL'];
    }
    $mail->SetFrom($senderEmail, $senderName);
    $mail->Subject = $subject;
    $mail->AltBody = strip_tags(str_replace('<br />', "\n", api_html_entity_decode($message)));
    // Send embedded image.
    if ($embedded_image) {
        // Get all images html inside content.
        preg_match_all("/<img\\s+.*?src=[\"\\']?([^\"\\' >]*)[\"\\']?[^>]*>/i", $message, $m);
        // Prepare new tag images.
        $new_images_html = array();
        $i = 1;
        if (!empty($m[1])) {
            foreach ($m[1] as $image_path) {
                $real_path = realpath($image_path);
                $filename = basename($image_path);
                $image_cid = $filename . '_' . $i;
                $encoding = 'base64';
                $image_type = mime_content_type($real_path);
                $mail->AddEmbeddedImage($real_path, $image_cid, $filename, $encoding, $image_type);
                $new_images_html[] = '<img src="cid:' . $image_cid . '" />';
                $i++;
            }
        }
        // Replace origin image for new embedded image html.
        $x = 0;
        if (!empty($m[0])) {
            foreach ($m[0] as $orig_img) {
                $message = str_replace($orig_img, $new_images_html[$x], $message);
                $x++;
            }
        }
    }
    $message = str_replace(array("\n\r", "\n", "\r"), '<br />', $message);
    $mailView = new Template(null, false, false, false, false, false, false);
    $mailView->assign('content', $message);
    $link = $additionalParameters['link'];
    $mailView->assign('link', $link);
    $layout = $mailView->get_template('mail/mail.tpl');
    $mail->Body = $mailView->fetch($layout);
    // Attachment ...
    if (!empty($data_file)) {
        $mail->AddAttachment($data_file['path'], $data_file['filename']);
    }
    // Only valid addresses are accepted.
    if (is_array($recipient_email)) {
        foreach ($recipient_email as $dest) {
            if (api_valid_email($dest)) {
                $mail->AddAddress($dest, $recipient_name);
            }
        }
    } else {
        if (api_valid_email($recipient_email)) {
            $mail->AddAddress($recipient_email, $recipient_name);
        } else {
            return 0;
        }
    }
    if (is_array($extra_headers) && count($extra_headers) > 0) {
        foreach ($extra_headers as $key => $value) {
            switch (strtolower($key)) {
                case 'encoding':
                case 'content-transfer-encoding':
                    $mail->Encoding = $value;
                    break;
                case 'charset':
                    $mail->Charset = $value;
                    break;
                case 'contenttype':
                case 'content-type':
                    $mail->ContentType = $value;
                    break;
                default:
                    $mail->AddCustomHeader($key . ':' . $value);
                    break;
            }
        }
    } else {
        if (!empty($extra_headers)) {
            $mail->AddCustomHeader($extra_headers);
        }
    }
    // WordWrap the html body (phpMailer only fixes AltBody) FS#2988
    $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap);
    // Send the mail message.
    if (!$mail->Send()) {
        error_log('ERROR: mail not sent to ' . $recipient_name . ' (' . $recipient_email . ') because of ' . $mail->ErrorInfo . '<br />');
        return 0;
    }
    if (!empty($additionalParameters)) {
        $plugin = new AppPlugin();
        $smsPlugin = $plugin->getSMSPluginLibrary();
        if ($smsPlugin) {
            $smsPlugin->send($additionalParameters);
        }
    }
    // Clear all the addresses.
    $mail->ClearAddresses();
    return 1;
}
Пример #2
0
/**
 * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
 * Sender name and email can be specified, if not specified
 * name and email of the platform admin are used
 *
 * @author Bert Vanderkimpen ICT&O UGent
 * @author Yannick Warnier <*****@*****.**>
 *
 * @param string    name of recipient
 * @param string    email of recipient
 * @param string    email subject
 * @param string    email body
 * @param string    sender name
 * @param string    sender e-mail
 * @param array     extra headers in form $headers = array($name => $value) to allow parsing
 * @param array     data file (path and filename)
 * @param array     data to attach a file (optional)
 * @param bool      True for attaching a embedded file inside content html (optional)
 * @return          returns true if mail was sent
 * @see             class.phpmailer.php
 */
function api_mail_html($recipient_name, $recipient_email, $subject, $message, $senderName = '', $senderEmail = '', $extra_headers = array(), $data_file = array(), $embedded_image = false, $additionalParameters = array())
{
    // Default values
    $notification = new Notification();
    $defaultEmail = $notification->getDefaultPlatformSenderEmail();
    $defaultName = $notification->getDefaultPlatformSenderName();
    // If the parameter is set don't use the admin.
    $senderName = !empty($senderName) ? $senderName : $defaultName;
    $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultEmail;
    $link = isset($additionalParameters['link']) ? $additionalParameters['link'] : '';
    $swiftMessage = \Swift_Message::newInstance()->setSubject($subject)->setFrom($senderEmail, $senderName)->setTo($recipient_email, $recipient_name)->setBody(Container::getTemplating()->render('ChamiloCoreBundle:default/mail:mail.html.twig', array('content' => $message, 'link' => $link)), 'text/html');
    if (!empty($additionalParameters)) {
        $plugin = new AppPlugin();
        $smsPlugin = $plugin->getSMSPluginLibrary();
        if ($smsPlugin) {
            $smsPlugin->send($additionalParameters);
        }
    }
    Container::getMailer()->send($swiftMessage);
    return 1;
}
Пример #3
0
/**
 * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
 * Sender name and email can be specified, if not specified
 * name and email of the platform admin are used
 *
 * @author Bert Vanderkimpen ICT&O UGent
 * @author Yannick Warnier <*****@*****.**>
 *
 * @param string    name of recipient
 * @param string    email of recipient
 * @param string    email subject
 * @param string    email body
 * @param string    sender name
 * @param string    sender e-mail
 * @param array     extra headers in form $headers = array($name => $value) to allow parsing
 * @param array     data file (path and filename)
 * @param array     data to attach a file (optional)
 * @param bool      True for attaching a embedded file inside content html (optional)
 * @return          returns true if mail was sent
 * @see             class.phpmailer.php
 */
function api_mail_html($recipient_name, $recipient_email, $subject, $body, $sender_name = '', $sender_email = '', $extra_headers = null, $data_file = array(), $embedded_image = false, $text_body = null)
{
    $reply_to_mail = $sender_email;
    $reply_to_name = $sender_name;
    if (isset($extra_headers['reply_to'])) {
        $reply_to_mail = $extra_headers['reply_to']['mail'];
        $reply_to_name = $extra_headers['reply_to']['name'];
    }
    // Forcing the conversion.
    if (strpos($body, '<html>') === false) {
        $htmlBody = str_replace(array("\n\r", "\n", "\r"), '<br />', $body);
        $htmlBody = '<html><head></head><body>' . $htmlBody . '</body></html>';
    } else {
        $htmlBody = $body;
    }
    if (!empty($text_body)) {
        $textBody = $text_body;
    } else {
        $textBody = $body;
    }
    try {
        $message = \Swift_Message::newInstance()->setSubject($subject)->setFrom(array($sender_email => $sender_name))->setTo(array($recipient_email => $recipient_name))->setReplyTo(array($reply_to_mail => $reply_to_name))->setBody(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:Default/default.html.twig', array('content' => $htmlBody)), 'text/html')->addPart(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:Default/default.text.twig', array('content' => $textBody)), 'text/plain')->setEncoder(Swift_Encoding::get8BitEncoding());
        if (!empty($data_file)) {
            // Attach it to the message
            $message->attach(Swift_Attachment::fromPath($data_file['path']))->setFilename($data_file['filename']);
        }
        $type = $message->getHeaders()->get('Content-Type');
        $type->setValue('text/html');
        $type->setParameter('charset', 'utf-8');
        Container::getMailer()->send($message);
        return true;
    } catch (Exception $e) {
        error_log($e->getMessage());
    }
    return false;
}
Пример #4
0
 /**
  * function register_course to create a record in the course table of the main database
  * @param string    $course_sys_code
  * @param string    $course_screen_code
  * @param string    $course_repository
  * @param string    $course_db_name
  * @param string    $tutor_name
  * @param string    $category
  * @param string    $title              complete name of course
  * @param string    $course_language    lang for this course
  * @param string    $uid                uid of owner
  * @param integer                       Expiration date in unix time representation
  * @param array                         Optional array of teachers' user ID
  * @return int      0
  * @todo use an array called $params instead of lots of params
  */
 static function register_course($params)
 {
     global $error_msg, $firstExpirationDelay;
     $title = $params['title'];
     $code = $params['code'];
     $visual_code = $params['visual_code'];
     $directory = isset($params['directory']) ? $params['directory'] : null;
     $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null;
     $category_code = isset($params['category_code']) ? $params['category_code'] : null;
     $defaultLanguage = Container::getTranslator()->getLocale();
     $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : $defaultLanguage;
     $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']);
     $department_name = isset($params['department_name']) ? $params['department_name'] : null;
     $department_url = isset($params['department_url']) ? $params['department_url'] : null;
     $disk_quota = isset($params['disk_quota']) ? $params['disk_quota'] : null;
     if (!isset($params['visibility'])) {
         $default_course_visibility = api_get_setting('course.courses_default_creation_visibility');
         if (isset($default_course_visibility)) {
             $visibility = $default_course_visibility;
         } else {
             $visibility = COURSE_VISIBILITY_OPEN_PLATFORM;
         }
     } else {
         $visibility = $params['visibility'];
     }
     $subscribe = isset($params['subscribe']) ? intval($params['subscribe']) : ($visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0);
     $unsubscribe = isset($params['unsubscribe']) ? intval($params['unsubscribe']) : 0;
     $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null;
     $teachers = isset($params['teachers']) ? $params['teachers'] : null;
     $status = isset($params['status']) ? $params['status'] : null;
     $TABLECOURSE = Database::get_main_table(TABLE_MAIN_COURSE);
     $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
     $ok_to_register_course = true;
     // Check whether all the needed parameters are present.
     if (empty($code)) {
         $error_msg[] = 'courseSysCode is missing';
         $ok_to_register_course = false;
     }
     if (empty($visual_code)) {
         $error_msg[] = 'courseScreenCode is missing';
         $ok_to_register_course = false;
     }
     if (empty($directory)) {
         $error_msg[] = 'courseRepository is missing';
         $ok_to_register_course = false;
     }
     if (empty($title)) {
         $error_msg[] = 'title is missing';
         $ok_to_register_course = false;
     }
     if (empty($expiration_date)) {
         $expiration_date = api_get_utc_datetime(time() + $firstExpirationDelay);
     } else {
         $expiration_date = api_get_utc_datetime($expiration_date);
     }
     if ($visibility < 0 || $visibility > 3) {
         $error_msg[] = 'visibility is invalid';
         $ok_to_register_course = false;
     }
     if (empty($disk_quota)) {
         $disk_quota = api_get_setting('document.default_document_quotum');
     }
     $time = api_get_utc_datetime();
     if (stripos($department_url, 'http://') === false && stripos($department_url, 'https://') === false) {
         $department_url = 'http://' . $department_url;
     }
     //just in case
     if ($department_url == 'http://') {
         $department_url = '';
     }
     $course_id = 0;
     if ($ok_to_register_course) {
         /** @var Course $course */
         $course = self::getCourseManager()->create();
         $course->setCode($code)->setDirectory($directory)->setCourseLanguage($course_language)->setTitle($title)->setDescription(get_lang('CourseDescription'))->setCategoryCode($category_code)->setVisibility($visibility)->setShowScore(1)->setDiskQuota($disk_quota)->setCreationDate(new \DateTime())->setExpirationDate(new \DateTime($expiration_date))->setDepartmentName($department_name)->setDepartmentUrl($department_url)->setSubscribe($subscribe)->setUnsubscribe($unsubscribe)->setVisualCode($visual_code);
         self::getCourseManager()->save($course, true);
         $course_id = $course->getId();
         /*// Here we must add 2 fields.
                   $sql = "INSERT INTO ".$TABLECOURSE . " SET
                         code            = '".Database :: escape_string($code) . "',
                         directory       = '".Database :: escape_string($directory) . "',
                         course_language = '".Database :: escape_string($course_language) . "',
                         title           = '".Database :: escape_string($title) . "',
                         description     = '".Database::escape_string(get_lang('CourseDescription')) . "',
                         category_code   = '".Database :: escape_string($category_code) . "',
                         visibility      = '".$visibility . "',
                         show_score      = '1',
                         disk_quota      = '".intval($disk_quota) . "',
                         creation_date   = '$time',
                         expiration_date = '".$expiration_date . "',
                         last_edit       = '$time',
                         last_visit      = NULL,
                         tutor_name      = '".Database :: escape_string($tutor_name) . "',
                         department_name = '".Database :: escape_string($department_name) . "',
                         department_url  = '".Database :: escape_string($department_url) . "',
                         subscribe       = '".intval($subscribe) . "',
                         unsubscribe     = '".intval($unsubscribe) . "',
                         visual_code     = '".Database :: escape_string($visual_code) . "'";
         
                     Database::query($sql);
                     $course_id  = Database::insert_id();*/
         //$course->addUsers()
         if ($course_id) {
             $settingsManager = Container::getCourseSettingsManager();
             $schemas = $settingsManager->getSchemas();
             $schemas = array_keys($schemas);
             /**
              * @var string $key
              * @var \Sylius\Bundle\SettingsBundle\Schema\SchemaInterface $schema
              */
             foreach ($schemas as $schema) {
                 $settings = $settingsManager->loadSettings($schema);
                 $settingsManager->setCourse($course);
                 $settingsManager->saveSettings($schema, $settings);
             }
             $sort = api_max_sort_value('0', api_get_user_id());
             $i_course_sort = CourseManager::userCourseSort($user_id, $code);
             if (!empty($user_id)) {
                 $sql = "INSERT INTO " . $TABLECOURSUSER . " SET\n                            c_id     = '" . Database::escape_string($course_id) . "',\n                            user_id         = '" . intval($user_id) . "',\n                            status          = '1',\n                            tutor_id        = '0',\n                            sort            = '" . $i_course_sort . "',\n                            user_course_cat = '0'";
                 Database::query($sql);
             }
             if (!empty($teachers)) {
                 if (!is_array($teachers)) {
                     $teachers = array($teachers);
                 }
                 foreach ($teachers as $key) {
                     //just in case
                     if ($key == $user_id) {
                         continue;
                     }
                     if (empty($key)) {
                         continue;
                     }
                     $sql = "INSERT INTO " . $TABLECOURSUSER . " SET\n                            c_id     = '" . Database::escape_string($course_id) . "',\n                            user_id         = '" . Database::escape_string($key) . "',\n                            status          = '1',\n                            role            = '',\n                            tutor_id        = '0',\n                            sort            = '" . ($sort + 1) . "',\n                            user_course_cat = '0'";
                     Database::query($sql);
                 }
             }
             // Adding the course to an URL
             if (api_is_multiple_url_enabled()) {
                 $url_id = 1;
                 if (api_get_current_access_url_id() != -1) {
                     $url_id = api_get_current_access_url_id();
                 }
                 UrlManager::add_course_to_url($course_id, $url_id);
             } else {
                 UrlManager::add_course_to_url($course_id, 1);
             }
             // Add event to the system log.
             $user_id = api_get_user_id();
             Event::addEvent(LOG_COURSE_CREATE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $code);
             $send_mail_to_admin = api_get_setting('course.send_email_to_admin_when_create_course');
             // @todo Improve code to send to all current portal administrators.
             if ($send_mail_to_admin == 'true') {
                 $siteName = api_get_setting('platform.site_name');
                 $recipient_email = api_get_setting('platform.administrator_email');
                 $recipient_name = api_get_person_name(api_get_setting('platform.administrator_name'), api_get_setting('platform.administrator_surname'));
                 $iname = api_get_setting('platform.institution');
                 $subject = get_lang('NewCourseCreatedIn') . ' ' . $siteName . ' - ' . $iname;
                 $body = get_lang('Dear') . ' ' . $recipient_name . ",\n\n" . get_lang('MessageOfNewCourseToAdmin') . ' ' . $siteName . ' - ' . $iname . "\n";
                 $body .= get_lang('CourseName') . ' ' . $title . "\n";
                 $body .= get_lang('Category') . ' ' . $category_code . "\n";
                 $body .= get_lang('Tutor') . ' ' . $tutor_name . "\n";
                 $body .= get_lang('Language') . ' ' . $course_language;
                 //api_mail_html($recipient_name, $recipient_email, $subject, $message, $siteName, $recipient_email);
                 $message = \Swift_Message::newInstance()->setSubject($subject)->setFrom($recipient_email)->setTo($recipient_email)->setBody(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:Course/new_course.html.twig', array('recipient_name' => $recipient_name, 'sitename' => $siteName, 'institution' => $iname, 'course_name' => $title, 'category' => $category_code, 'tutor' => $tutor_name, 'language' => $course_language)));
                 Container::getMailer()->send($message);
             }
         }
     }
     return $course_id;
 }
Пример #5
0
 /**
  * Creates a new user for the platform
  * @author Hugues Peeters <*****@*****.**>,
  * @author Roan Embrechts <*****@*****.**>
  * @param   string    Firstname
  * @param   string    Lastname
  * @param   int       Status (1 for course tutor, 5 for student, 6 for anonymous)
  * @param   string    e-mail address
  * @param   string    Login
  * @param   string    Password
  * @param   string    Any official code (optional)
  * @param   string    User language    (optional)
  * @param   string    Phone number    (optional)
  * @param   string    Picture URI        (optional)
  * @param   string    Authentication source    (optional, defaults to 'platform', dependind on constant)
  * @param   string    Account expiration date (optional, defaults to '0000-00-00 00:00:00')
  * @param   int        Whether the account is enabled or disabled by default
  * @param   int        The department of HR in which the user is registered (optional, defaults to 0)
  * @param   array    Extra fields
  * @param   string    Encrypt method used if password is given encrypted. Set to an empty string by default
  * @return  mixed   new user id - if the new user creation succeeds, false otherwise
  * @desc The function tries to retrieve $_user['user_id'] from the global space. If it exists, $_user['user_id'] is the creator id. If a problem arises, it stores the error message in global $api_failureList
  * @assert ('Sam','Gamegie',5,'*****@*****.**','jo','jo') > 1
  * @assert ('Pippin','Took',null,null,'jo','jo') === false
  */
 public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expiration_date = '0000-00-00 00:00:00', $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false)
 {
     global $_configuration;
     $original_password = $password;
     $access_url_id = 1;
     if (api_get_multiple_access_url()) {
         $access_url_id = api_get_current_access_url_id();
     }
     if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) {
         $num = self::get_number_of_users();
         if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
             return api_set_failure('portal users limit reached');
         }
     }
     if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0) {
         $num = self::get_number_of_users(1);
         if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
             return api_set_failure('portal teachers limit reached');
         }
     }
     $firstName = Security::remove_XSS($firstName);
     $lastName = Security::remove_XSS($lastName);
     $loginName = Security::remove_XSS($loginName);
     $phone = Security::remove_XSS($phone);
     // database table definition
     $table_user = Database::get_main_table(TABLE_MAIN_USER);
     //Checking the user language
     $languages = api_get_languages();
     if (!in_array($language, $languages)) {
         $language = Container::getTranslator()->getLocale();
     }
     $creator_id = api_get_user_id();
     // First check wether the login already exists
     if (!self::is_username_available($loginName)) {
         return api_set_failure('login-pass already taken');
     }
     if (empty($encrypt_method)) {
         $password = api_get_encrypted_password($password);
     } else {
         if ($_configuration['password_encryption'] === $encrypt_method) {
             if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
                 return api_set_failure('encrypt_method invalid');
             } else {
                 if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
                     return api_set_failure('encrypt_method invalid');
                 }
             }
         } else {
             return api_set_failure('encrypt_method invalid');
         }
     }
     //@todo replace this date with the api_get_utc_date function big problem with users that are already registered
     $current_date = api_get_utc_datetime();
     $em = Database::getManager();
     $expirationDate = new \DateTime($expiration_date);
     $user = new \Chamilo\UserBundle\Entity\User();
     $user->setLastname($lastName)->setFirstname($firstName)->setUsername($loginName)->setPassword($password)->setEmail($email)->setOfficialCode($official_code)->setPictureUri($picture_uri)->setCreatorId($creator_id)->setAuthSource($auth_source)->setPhone($phone)->setLanguage($language)->setExpirationDate($expirationDate)->setHrDeptId($hr_dept_id)->setActive($active);
     /*$sql = "INSERT INTO $table_user ".
              "SET lastname =         '".Database::escape_string(trim($lastName))."',".
              "firstname =         '".Database::escape_string(trim($firstName))."',".
              "username =            '******',".
              "status =             '".Database::escape_string($status)."',".
              "password =             '******',".
              "email =             '".Database::escape_string($email)."',".
              "official_code    =     '".Database::escape_string($official_code)."',".
              "picture_uri     =     '".Database::escape_string($picture_uri)."',".
              "creator_id      =     '".Database::escape_string($creator_id)."',".
              "auth_source =         '".Database::escape_string($auth_source)."',".
              "phone =             '".Database::escape_string($phone)."',".
              "language =             '".Database::escape_string($language)."',".
              "registration_date = '".$current_date."',".
              "expiration_date =     '".Database::escape_string($expiration_date)."',".
              "hr_dept_id =         '".Database::escape_string($hr_dept_id)."',".
              "active =             '".Database::escape_string($active)."'";
       $result = Database::query($sql);*/
     $em->persist($user);
     $em->flush();
     if ($user) {
         $userId = $user->getId();
         if (api_get_multiple_access_url()) {
             UrlManager::add_user_to_url($userId, api_get_current_access_url_id());
         } else {
             //we are adding by default the access_url_user table with access_url_id = 1
             UrlManager::add_user_to_url($userId, 1);
         }
         $group = $em->getRepository('ChamiloUserBundle:Group')->find($status);
         $user->addGroup($group);
         //$user->addRole($roleName);
         $em->persist($user);
         $em->flush();
         if (!empty($email) && $send_mail) {
             $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS);
             $emailsubject = '[' . api_get_setting('platform.site_name') . '] ' . get_lang('YourReg') . ' ' . api_get_setting('platform.site_name');
             $sender_name = api_get_person_name(api_get_setting('platform.administrator_name'), api_get_setting('platform.administrator_surname'), null, PERSON_NAME_EMAIL_ADDRESS);
             $email_admin = api_get_setting('platform.administrator_email');
             $params = array('complete_user_name' => api_get_person_name($firstName, $lastName), 'login_name' => $loginName, 'password' => stripslashes($original_password));
             $message = \Swift_Message::newInstance()->setSubject($emailsubject)->setFrom(array($email_admin => $sender_name))->setTo(array($email => $recipient_name))->setBody(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:User/new_user.html.twig', $params), 'text/html')->addPart(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:User/new_user.text.twig', $params), 'text/plain')->setEncoder(Swift_Encoding::get8BitEncoding());
             $type = $message->getHeaders()->get('Content-Type');
             $type->setValue('text/html');
             $type->setParameter('charset', 'utf-8');
             Container::getMailer()->send($message);
             /* MANAGE EVENT WITH MAIL */
             /*if (EventsMail::check_if_using_class('user_registration')) {
                   $values["about_user"] = $return;
                   $values["password"] = $original_password;
                   $values["send_to"] = array($return);
                   $values["prior_lang"] = null;
                   EventsDispatcher::events('user_registration', $values);
               } else {
                   @api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
               }*/
             /* ENDS MANAGE EVENT WITH MAIL */
         }
         // Add event to system log
         $user_id_manager = api_get_user_id();
         $user_info = api_get_user_info($userId);
         Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $userId, api_get_utc_datetime(), $user_id_manager);
         Event::addEvent(LOG_USER_CREATE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id_manager);
     } else {
         return api_set_failure('error inserting in Database');
     }
     if (is_array($extra) && count($extra) > 0) {
         $res = true;
         foreach ($extra as $fname => $fvalue) {
             $res = $res && self::update_extra_field_value($userId, $fname, $fvalue);
         }
     }
     self::update_extra_field_value($userId, 'already_logged_in', 'false');
     return $userId;
 }