rellapdrella

Contao 3 ModuleRegistration.php

Feb 2nd, 2013
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.02 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Contao Open Source CMS
  5.  *
  6.  * Copyright (C) 2005-2013 Leo Feyer
  7.  *
  8.  * @package Core
  9.  * @link    https://contao.org
  10.  * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
  11.  */
  12.  
  13.  
  14. /**
  15.  * Run in a custom namespace, so the class can be replaced
  16.  */
  17. namespace Contao;
  18.  
  19.  
  20. /**
  21.  * Class ModuleRegistration
  22.  *
  23.  * Front end module "registration".
  24.  * @copyright  Leo Feyer 2005-2013
  25.  * @author     Leo Feyer <https://contao.org>
  26.  * @package    Core
  27.  */
  28. class ModuleRegistration extends \Module
  29. {
  30.  
  31.     /**
  32.      * Template
  33.      * @var string
  34.      */
  35.     protected $strTemplate = 'member_default';
  36.  
  37.  
  38.     /**
  39.      * Display a wildcard in the back end
  40.      * @return string
  41.      */
  42.     public function generate()
  43.     {
  44.         if (TL_MODE == 'BE')
  45.         {
  46.             $objTemplate = new \BackendTemplate('be_wildcard');
  47.  
  48.             $objTemplate->wildcard = '### USER REGISTRATION ###';
  49.             $objTemplate->title = $this->headline;
  50.             $objTemplate->id = $this->id;
  51.             $objTemplate->link = $this->name;
  52.             $objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;
  53.  
  54.             return $objTemplate->parse();
  55.         }
  56.  
  57.         $this->editable = deserialize($this->editable);
  58.  
  59.         // Return if there are no editable fields
  60.         if (!is_array($this->editable) || empty($this->editable))
  61.         {
  62.             return '';
  63.         }
  64.  
  65.         return parent::generate();
  66.     }
  67.  
  68.  
  69.     /**
  70.      * Generate the module
  71.      */
  72.     protected function compile()
  73.     {
  74.         global $objPage;
  75.  
  76.         $GLOBALS['TL_LANGUAGE'] = $objPage->language;
  77.  
  78.         $this->loadLanguageFile('tl_member');
  79.         $this->loadDataContainer('tl_member');
  80.  
  81.         // Call onload_callback (e.g. to check permissions)
  82.         if (is_array($GLOBALS['TL_DCA']['tl_member']['config']['onload_callback']))
  83.         {
  84.             foreach ($GLOBALS['TL_DCA']['tl_member']['config']['onload_callback'] as $callback)
  85.             {
  86.                 if (is_array($callback))
  87.                 {
  88.                     $this->import($callback[0]);
  89.                     $this->$callback[0]->$callback[1]();
  90.                 }
  91.             }
  92.         }
  93.  
  94.         // Activate account
  95.         if (\Input::get('token') != '')
  96.         {
  97.             $this->activateAcount();
  98.             return;
  99.         }
  100.  
  101.         if ($this->memberTpl != '')
  102.         {
  103.             $this->Template = new \FrontendTemplate($this->memberTpl);
  104.             $this->Template->setData($this->arrData);
  105.         }
  106.  
  107.         $this->Template->fields = '';
  108.         $this->Template->tableless = $this->tableless;
  109.         $objCaptcha = null;
  110.         $doNotSubmit = false;
  111.  
  112.         // Captcha
  113.         if (!$this->disableCaptcha)
  114.         {
  115.             $arrCaptcha = array
  116.             (
  117.                 'id' => 'registration',
  118.                 'label' => $GLOBALS['TL_LANG']['MSC']['securityQuestion'],
  119.                 'type' => 'captcha',
  120.                 'mandatory' => true,
  121.                 'required' => true,
  122.                 'tableless' => $this->tableless
  123.             );
  124.  
  125.             $strClass = $GLOBALS['TL_FFL']['captcha'];
  126.  
  127.             // Fallback to default if the class is not defined
  128.             if (!class_exists($strClass))
  129.             {
  130.                 $strClass = 'FormCaptcha';
  131.             }
  132.  
  133.             $objCaptcha = new $strClass($arrCaptcha);
  134.  
  135.             if (\Input::post('FORM_SUBMIT') == 'tl_registration')
  136.             {
  137.                 $objCaptcha->validate();
  138.  
  139.                 if ($objCaptcha->hasErrors())
  140.                 {
  141.                     $doNotSubmit = true;
  142.                 }
  143.             }
  144.         }
  145.  
  146.         $arrUser = array();
  147.         $arrFields = array();
  148.         $hasUpload = false;
  149.         $i = 0;
  150.  
  151.         // Build form
  152.         foreach ($this->editable as $field)
  153.         {
  154.             $arrData = $GLOBALS['TL_DCA']['tl_member']['fields'][$field];
  155.  
  156.             // Map checkboxWizard to regular checkbox widget
  157.             if ($arrData['inputType'] == 'checkboxWizard')
  158.             {
  159.                 $arrData['inputType'] = 'checkbox';
  160.             }
  161.  
  162.             $strClass = $GLOBALS['TL_FFL'][$arrData['inputType']];
  163.  
  164.             // Continue if the class is not defined
  165.             if (!class_exists($strClass))
  166.             {
  167.                 continue;
  168.             }
  169.  
  170.             $arrData['eval']['tableless'] = $this->tableless;
  171.             $arrData['eval']['required'] = $arrData['eval']['mandatory'];
  172.  
  173.             $objWidget = new $strClass($this->prepareForWidget($arrData, $field, $arrData['default']));
  174.             $objWidget->storeValues = true;
  175.             $objWidget->rowClass = 'row_' . $i . (($i == 0) ? ' row_first' : '') . ((($i % 2) == 0) ? ' even' : ' odd');
  176.  
  177.             // Increase the row count if its a password field
  178.             if ($objWidget instanceof \FormPassword)
  179.             {
  180.                 $objWidget->rowClassConfirm = 'row_' . ++$i . ((($i % 2) == 0) ? ' even' : ' odd');
  181.             }
  182.  
  183.             // Validate input
  184.             if (\Input::post('FORM_SUBMIT') == 'tl_registration')
  185.             {
  186.                 $objWidget->validate();
  187.                 $varValue = $objWidget->value;
  188.  
  189.                 // Check whether the password matches the username
  190.                 if ($objWidget instanceof \FormPassword && $varValue == \Input::post('username'))
  191.                 {
  192.                     $objWidget->addError($GLOBALS['TL_LANG']['ERR']['passwordName']);
  193.                 }
  194.  
  195.                 $rgxp = $arrData['eval']['rgxp'];
  196.  
  197.                 // Convert date formats into timestamps (check the eval setting first -> #3063)
  198.                 if (($rgxp == 'date' || $rgxp == 'time' || $rgxp == 'datim') && $varValue != '')
  199.                 {
  200.                     // Use the numeric back end format here!
  201.                     $objDate = new \Date($varValue, $GLOBALS['TL_CONFIG'][$rgxp.'Format']);
  202.                     $varValue = $objDate->tstamp;
  203.                 }
  204.  
  205.                 // Make sure that unique fields are unique (check the eval setting first -> #3063)
  206.                 if ($arrData['eval']['unique'] && $varValue != '' && !$this->Database->isUniqueValue('tl_member', $field, $varValue))
  207.                 {
  208.                     $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $arrData['label'][0] ?: $field));
  209.                 }
  210.  
  211.                 // Save callback
  212.                 if (is_array($arrData['save_callback']))
  213.                 {
  214.                     foreach ($arrData['save_callback'] as $callback)
  215.                     {
  216.                         $this->import($callback[0]);
  217.  
  218.                         try
  219.                         {
  220.                             $varValue = $this->$callback[0]->$callback[1]($varValue, $this->User);
  221.                         }
  222.                         catch (\Exception $e)
  223.                         {
  224.                             $objWidget->class = 'error';
  225.                             $objWidget->addError($e->getMessage());
  226.                         }
  227.                     }
  228.                 }
  229.  
  230.                 // Store the current value
  231.                 if ($objWidget->hasErrors())
  232.                 {
  233.                     $doNotSubmit = true;
  234.                 }
  235.                 elseif ($objWidget->submitInput())
  236.                 {
  237.                     $arrUser[$field] = $varValue;
  238.                 }
  239.             }
  240.  
  241.             if ($objWidget instanceof \uploadable)
  242.             {
  243.                 $hasUpload = true;
  244.             }
  245.  
  246.             $temp = $objWidget->parse();
  247.  
  248.             $this->Template->fields .= $temp;
  249.             $arrFields[$arrData['eval']['feGroup']][$field] .= $temp;
  250.  
  251.             ++$i;
  252.         }
  253.  
  254.         // Captcha
  255.         if (!$this->disableCaptcha)
  256.         {
  257.             $objCaptcha->rowClass = 'row_'.$i . (($i == 0) ? ' row_first' : '') . ((($i % 2) == 0) ? ' even' : ' odd');
  258.             $strCaptcha = $objCaptcha->parse();
  259.  
  260.             $this->Template->fields .= $strCaptcha;
  261.             $arrFields['captcha'] .= $strCaptcha;
  262.         }
  263.  
  264.         $this->Template->rowLast = 'row_' . ++$i . ((($i % 2) == 0) ? ' even' : ' odd');
  265.         $this->Template->enctype = $hasUpload ? 'multipart/form-data' : 'application/x-www-form-urlencoded';
  266.         $this->Template->hasError = $doNotSubmit;
  267.  
  268.         // Create new user if there are no errors
  269.         if (\Input::post('FORM_SUBMIT') == 'tl_registration' && !$doNotSubmit)
  270.         {
  271.             $this->createNewUser($arrUser);
  272.         }
  273.  
  274.         $this->Template->loginDetails = $GLOBALS['TL_LANG']['tl_member']['loginDetails'];
  275.         $this->Template->addressDetails = $GLOBALS['TL_LANG']['tl_member']['addressDetails'];
  276.         $this->Template->contactDetails = $GLOBALS['TL_LANG']['tl_member']['contactDetails'];
  277.         $this->Template->personalData = $GLOBALS['TL_LANG']['tl_member']['personalData'];
  278.         $this->Template->captchaDetails = $GLOBALS['TL_LANG']['MSC']['securityQuestion'];
  279.  
  280.         // Add groups
  281.         foreach ($arrFields as $k=>$v)
  282.         {
  283.             $this->Template->$k = $v;
  284.         }
  285.  
  286.         $this->Template->captcha = $arrFields['captcha'];
  287.         $this->Template->formId = 'tl_registration';
  288.         $this->Template->slabel = specialchars($GLOBALS['TL_LANG']['MSC']['register']);
  289.         $this->Template->action = $this->getIndexFreeRequest();
  290.  
  291.         // HOOK: add memberlist fields
  292.         if (in_array('memberlist', $this->Config->getActiveModules()))
  293.         {
  294.             $this->Template->profile = $arrFields['profile'];
  295.             $this->Template->profileDetails = $GLOBALS['TL_LANG']['tl_member']['profileDetails'];
  296.         }
  297.  
  298.         // HOOK: add newsletter fields
  299.         if (in_array('newsletter', $this->Config->getActiveModules()))
  300.         {
  301.             $this->Template->newsletter = $arrFields['newsletter'];
  302.             $this->Template->newsletterDetails = $GLOBALS['TL_LANG']['tl_member']['newsletterDetails'];
  303.         }
  304.  
  305.         // HOOK: add helpdesk fields
  306.         if (in_array('helpdesk', $this->Config->getActiveModules()))
  307.         {
  308.             $this->Template->helpdesk = $arrFields['helpdesk'];
  309.             $this->Template->helpdeskDetails = $GLOBALS['TL_LANG']['tl_member']['helpdeskDetails'];
  310.         }
  311.     }
  312.  
  313.  
  314.     /**
  315.      * Create a new user and redirect
  316.      * @param array
  317.      */
  318.     protected function createNewUser($arrData)
  319.     {
  320.         $arrData['tstamp'] = time();
  321.         $arrData['login'] = $this->reg_allowLogin;
  322.         $arrData['activation'] = md5(uniqid(mt_rand(), true));
  323.         $arrData['dateAdded'] = $arrData['tstamp'];
  324.  
  325.         // Set default groups
  326.         if (!array_key_exists('groups', $arrData))
  327.         {
  328.             $arrData['groups'] = $this->reg_groups;
  329.         }
  330.  
  331.         // Disable account
  332.         $arrData['disable'] = 1;
  333.  
  334.         // Send activation e-mail
  335.         if ($this->reg_activate)
  336.         {
  337.             $arrChunks = array();
  338.  
  339.             $strConfirmation = $this->reg_text;
  340.             preg_match_all('/##[^#]+##/', $strConfirmation, $arrChunks);
  341.  
  342.             foreach ($arrChunks[0] as $strChunk)
  343.             {
  344.                 $strKey = substr($strChunk, 2, -2);
  345.  
  346.                 switch ($strKey)
  347.                 {
  348.                     case 'domain':
  349.                         $strConfirmation = str_replace($strChunk, \Environment::get('host'), $strConfirmation);
  350.                         break;
  351.  
  352.                     case 'link':
  353.                         $strConfirmation = str_replace($strChunk, \Environment::get('base') . \Environment::get('request') . (($GLOBALS['TL_CONFIG']['disableAlias'] || strpos(\Environment::get('request'), '?') !== false) ? '&' : '?') . 'token=' . $arrData['activation'], $strConfirmation);
  354.                         break;
  355.  
  356.                     // HOOK: support newsletter subscriptions
  357.                     case 'channel':
  358.                     case 'channels':
  359.                         if (!in_array('newsletter', $this->Config->getActiveModules()))
  360.                         {
  361.                             break;
  362.                         }
  363.  
  364.                         // Make sure newsletter is an array
  365.                         if (!is_array($arrData['newsletter']))
  366.                         {
  367.                             if ($arrData['newsletter'] != '')
  368.                             {
  369.                                 $arrData['newsletter'] = array($arrData['newsletter']);
  370.                             }
  371.                             else
  372.                             {
  373.                                 $arrData['newsletter'] = array();
  374.                             }
  375.                         }
  376.  
  377.                         // Replace the wildcard
  378.                         if (!empty($arrData['newsletter']))
  379.                         {
  380.                             $objChannels = \NewsletterChannelModel::findByIds($arrData['newsletter']);
  381.  
  382.                             if ($objChannels !== null)
  383.                             {
  384.                                 $strConfirmation = str_replace($strChunk, implode("\n", $objChannels->fetchEach('title')), $strConfirmation);
  385.                             }
  386.                         }
  387.                         else
  388.                         {
  389.                             $strConfirmation = str_replace($strChunk, '', $strConfirmation);
  390.                         }
  391.                         break;
  392.  
  393.                     default:
  394.                         $strConfirmation = str_replace($strChunk, $arrData[$strKey], $strConfirmation);
  395.                         break;
  396.                 }
  397.             }
  398.  
  399.             $objEmail = new \Email();
  400.  
  401.             $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
  402.             $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
  403.             $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['emailSubject'], \Environment::get('host'));
  404.             $objEmail->text = $strConfirmation;
  405.             $objEmail->sendTo($arrData['email']);
  406.         }
  407.  
  408.         // Make sure newsletter is an array
  409.         if (isset($arrData['newsletter']) && !is_array($arrData['newsletter']))
  410.         {
  411.             $arrData['newsletter'] = array($arrData['newsletter']);
  412.         }
  413.  
  414.         // Create the user
  415.         $objNewUser = new \MemberModel();
  416.         $objNewUser->setRow($arrData);
  417.         $objNewUser->save();
  418.         $insertId = $objNewUser->id;
  419.  
  420.         // Assign home directory
  421.         if ($this->reg_assignDir && is_dir(TL_ROOT . '/' . $this->reg_homeDir))
  422.         {
  423.             $this->import('Files');
  424.             $strUserDir = $arrData['username'] ?: 'user_' . $insertId;
  425.  
  426.             // Add the user ID if the directory exists
  427.             if (is_dir(TL_ROOT . '/' . $this->reg_homeDir . '/' . $strUserDir))
  428.             {
  429.                 $strUserDir .= '_' . $insertId;
  430.             }
  431.  
  432.             new \Folder($this->reg_homeDir . '/' . $strUserDir);
  433.  
  434.             $objNewUser->assignDir = 1;
  435.             $objNewUser->homeDir = $this->reg_homeDir . '/' . $strUserDir;
  436.             $objNewUser->save();
  437.         }
  438.  
  439.         // HOOK: send insert ID and user data
  440.         if (isset($GLOBALS['TL_HOOKS']['createNewUser']) && is_array($GLOBALS['TL_HOOKS']['createNewUser']))
  441.         {
  442.             foreach ($GLOBALS['TL_HOOKS']['createNewUser'] as $callback)
  443.             {
  444.                 $this->import($callback[0]);
  445.                 $this->$callback[0]->$callback[1]($insertId, $arrData, $this);
  446.             }
  447.         }
  448.  
  449.         // Inform admin if no activation link is sent
  450.         if (!$this->reg_activate)
  451.         {
  452.             $this->sendAdminNotification($insertId, $arrData);
  453.         }
  454.  
  455.         $this->jumpToOrReload($this->objModel->getRelated('jumpTo')->row());
  456.     }
  457.  
  458.  
  459.     /**
  460.      * Activate an account
  461.      */
  462.     protected function activateAcount()
  463.     {
  464.         $this->strTemplate = 'mod_message';
  465.         $this->Template = new \FrontendTemplate($this->strTemplate);
  466.  
  467.         // Check the token
  468.         $objMember = \MemberModel::findByActivation(\Input::get('token'));
  469.  
  470.         if ($objMember === null)
  471.         {
  472.             $this->Template->type = 'error';
  473.             $this->Template->message = $GLOBALS['TL_LANG']['MSC']['accountError'];
  474.             return;
  475.         }
  476.  
  477.         // Update the account
  478.         $objMember->disable = '';
  479.         $objMember->activation = '';
  480.         $objMember->save();
  481.  
  482.         // HOOK: post activation callback
  483.         if (isset($GLOBALS['TL_HOOKS']['activateAccount']) && is_array($GLOBALS['TL_HOOKS']['activateAccount']))
  484.         {
  485.             foreach ($GLOBALS['TL_HOOKS']['activateAccount'] as $callback)
  486.             {
  487.                 $this->import($callback[0]);
  488.                 $this->$callback[0]->$callback[1]($objMember, $this);
  489.             }
  490.         }
  491.  
  492.         $arrData = array();
  493.  
  494.         // Get the editable fields
  495.         foreach ($this->editable as $key)
  496.         {
  497.             $arrData[$key] = $objMember->$key;
  498.         }
  499.  
  500.         // Add the login details
  501.         $arrData['login'] = $objMember->login;
  502.         $arrData['groups'] = $objMember->groups;
  503.         $arrData['disable'] = '';
  504.  
  505.         // Log activity
  506.         $this->log('User account ID ' . $objMember->id . ' (' . $objMember->email . ') has been activated', 'ModuleRegistration activateAccount()', TL_ACCESS);
  507.  
  508.         // Redirect to the jumpTo page
  509.         if (($objTarget = $this->objModel->getRelated('reg_jumpTo')) !== null)
  510.         {
  511.             $this->redirect($this->generateFrontendUrl($objTarget->row()));
  512.         }
  513.  
  514.         // Confirm activation
  515.         $this->Template->type = 'confirm';
  516.         $this->Template->message = $GLOBALS['TL_LANG']['MSC']['accountActivated'];
  517.     }
  518.  
  519.  
  520.     /**
  521.      * Send an admin notification e-mail
  522.      * @param integer
  523.      * @param array
  524.      */
  525.     protected function sendAdminNotification($intId, $arrData)
  526.     {
  527.         $objEmail = new \Email();
  528.  
  529.         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
  530.         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
  531.         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['adminSubject'], \Environment::get('host'));
  532.  
  533.         $strData = "\n\n";
  534.  
  535.         // Add user details
  536.         foreach ($arrData as $k=>$v)
  537.         {
  538.             if ($k == 'password' || $k == 'tstamp' || $k == 'activation')
  539.             {
  540.                 continue;
  541.             }
  542.  
  543.             $v = deserialize($v);
  544.  
  545.             if ($k == 'dateOfBirth' && strlen($v))
  546.             {
  547.                 $v = $this->parseDate($GLOBALS['TL_CONFIG']['dateFormat'], $v);
  548.             }
  549.  
  550.             $strData .= $GLOBALS['TL_LANG']['tl_member'][$k][0] . ': ' . (is_array($v) ? implode(', ', $v) : $v) . "\n";
  551.         }
  552.  
  553.         $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['adminText'], $intId, $strData . "\n") . "\n";
  554.         $objEmail->sendTo($GLOBALS['TL_ADMIN_EMAIL']);
  555.  
  556.         $this->log('A new user (ID ' . $intId . ') has registered on the website', 'ModuleRegistration sendAdminNotification()', TL_ACCESS);
  557.     }
  558. }
Advertisement
Add Comment
Please, Sign In to add comment