Example #1
0
 /**
  * Singleton
  *
  * @return MageBridgeModelUser $_instance
  */
 public static function getInstance()
 {
     static $instance;
     if (null === self::$_instance) {
         self::$_instance = new self();
     }
     return self::$_instance;
 }
Example #2
0
 /**
  * Method to handle the upload of a new CSV-file
  *
  * @param null
  * @return array
  */
 public function upload()
 {
     // Construct the needed variables
     $upload = JFactory::getApplication()->input->getVar('csv', null, 'files');
     $user_records_ok = 0;
     $user_records_fail = 0;
     // Check whether this is a valid download
     if (empty($upload) || empty($upload['name']) || empty($upload['tmp_name']) || empty($upload['size'])) {
         $this->setRedirect('index.php?option=com_magebridge&view=users&task=import', JText::_('File upload failed on system level'), 'error');
         return false;
     }
     // Check for empty content
     $csv = @file_get_contents($upload['tmp_name']);
     if (empty($csv)) {
         $this->setRedirect('index.php?option=com_magebridge&view=users&task=import', JText::_('Empty file upload'), 'error');
         return false;
     }
     // Turn the CSV-content into a workable array
     $lines = explode("\n", $csv);
     if (!empty($lines)) {
         // Parse the header of this CSV file
         $header = $this->parseLine(array_shift($lines));
         // Extract usable user-fields from this header
         $email = array_search('email', $header);
         $firstname = array_search('firstname', $header);
         $lastname = array_search('lastname', $header);
         // Loop through the other lines to fetch the usable user-fields
         foreach ($lines as $line) {
             if (empty($line)) {
                 continue;
             }
             $fields = $this->parseLine($line);
             $user = array('email' => $fields[$email], 'firstname' => $fields[$firstname], 'lastname' => $fields[$lastname]);
             $user = MageBridgeUserHelper::convert($user);
             $rt = MageBridgeModelUser::create($user, true);
             if ($rt == true) {
                 $user_records_ok++;
             } else {
                 $user_records_fail++;
             }
         }
     }
     $this->setRedirect('index.php?option=com_magebridge&view=users', JText::sprintf('Imported %d users succesfully, %d users failed', $user_records_ok, $user_records_fail));
     return true;
 }
Example #3
0
 /**
  * CURL-wrapper
  * 
  * @param string $url
  * @param string $type
  * @param array $arguments
  * @param boolean @run_bridge
  *                
  * @return string
  */
 public function getCURL($url, $type = 'get', $arguments = null, $runBridge = false)
 {
     // Load variables
     $httpHeaders = array();
     // Initialize CURL
     $handle = curl_init($url);
     if ($handle == false) {
         return null;
     }
     curl_setopt_array($handle, $this->getCurlDefaultArguments());
     $this->setCurlHeaders($handle);
     $this->setCurlHttpAuthentication($handle);
     // Forward cookies to Magento
     if ($runBridge == true) {
         $this->setCurlCookies($handle);
     }
     // Detect whether certain HTTP headers are set by the client
     foreach ($_SERVER as $header => $value) {
         if (!preg_match('/^http_/i', $header)) {
             continue;
         }
         $header = strtoupper(preg_replace('/http_/i', '', $header));
         if ($header == 'X_REQUESTED_WITH') {
             $httpHeaders[] = 'X-REQUESTED-WITH' . ': ' . $value;
         } else {
             if (preg_match('/^ACCEPT_/', $header)) {
                 $httpHeaders[] = str_replace('_', '-', $header) . ': ' . $value;
             }
         }
     }
     // Add proxy HTTP headers
     if (isset($_SERVER['REMOTE_ADDR'])) {
         $httpHeaders[] = 'X-REAL-IP: ' . $_SERVER['REMOTE_ADDR'];
     }
     if (isset($_SERVER['REMOTE_ADDR'])) {
         $httpHeaders[] = 'X-FORWARDED-FOR: ' . $_SERVER['REMOTE_ADDR'];
     }
     if (isset($_SERVER['SERVER_ADDR'])) {
         $httpHeaders[] = 'VIA: ' . $_SERVER['SERVER_ADDR'];
     }
     // Set SSL options
     $uri = JURI::getInstance();
     if ($uri->isSSL() == true) {
         $httpHeaders[] = 'FRONT-END-HTTPS: On';
     }
     if ($uri->isSSL() == true) {
         $httpHeaders[] = 'X-FORWARD-PROTO: https';
     }
     // Add some extra HTTP headers for HTTP Keep Alive
     if (MagebridgeModelConfig::load('keep_alive') == 0) {
         $httpHeaders[] = 'Connection: close';
     } else {
         $httpHeaders[] = 'Connection: keep-alive';
     }
     // Spoof the browser
     if (MagebridgeModelConfig::load('spoof_browser') == 1) {
         if ($runBridge == true && $this->app->isSite() == 1) {
             curl_setopt($handle, CURLOPT_REFERER, MageBridgeUrlHelper::getRequest());
             curl_setopt($handle, CURLOPT_USERAGENT, isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
         } else {
             curl_setopt($handle, CURLOPT_USERAGENT, $this->getUserAgentBySystem());
         }
     }
     // Automatically handle file uploads
     $tmp_files = $this->helper->upload();
     if (!empty($tmp_files)) {
         foreach ($tmp_files as $name => $tmp_file) {
             if (class_exists('CurlFile')) {
                 $arguments[$name] = new CurlFile($tmp_file['tmp_name'], $tmp_file['type']);
             } else {
                 $arguments[$name] = '@' . $tmp_file['tmp_name'];
             }
         }
     }
     // Set extra options when a POST is handled
     if ($type == 'post') {
         $arguments = is_array($arguments) && MagebridgeModelConfig::load('curl_post_as_array') == 0 ? http_build_query($arguments) : $arguments;
         curl_setopt($handle, CURLOPT_POST, true);
         curl_setopt($handle, CURLOPT_POSTFIELDS, $arguments);
         $httpHeaders[] = 'Expect:';
         //print_r($arguments);exit;
     }
     // Add the HTTP headers
     curl_setopt($handle, CURLOPT_HTTPHEADER, $httpHeaders);
     // Set encoding to zero
     curl_setopt($handle, CURLOPT_ENCODING, '');
     // Handle direct output and bridge output
     $this->debug->notice('CURL init: ' . $url . ' (' . (MageBridgeUrlHelper::getRequest() ? MageBridgeUrlHelper::getRequest() : 'no request') . ')');
     $this->handleFileDownloads($handle);
     $data = curl_exec($handle);
     $size = YireoHelper::strlen($data);
     if ($size > 1024) {
         $size = round($size / 1024, 2) . 'Kb';
     }
     $this->debug->profiler('CURL response size: ' . $size);
     // Cleanup the temporary uploads
     $this->helper->cleanup($tmp_files);
     // Separate the headers from the body
     $this->head['header_found'] = false;
     $this->head['last_url'] = curl_getinfo($handle, CURLINFO_EFFECTIVE_URL);
     $this->head['http_code'] = curl_getinfo($handle, CURLINFO_HTTP_CODE);
     $this->head['size'] = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
     $this->head['info'] = curl_getinfo($handle);
     // Determine the separator
     $separator = null;
     if (strpos($data, "\r\n\r\n") > 0) {
         $separator = "\r\n\r\n";
     } elseif (strpos($data, "\n\n") > 0) {
         $separator = "\n\n";
     }
     // Split data into segments
     if (strpos($data, $separator) > 0) {
         $dataSegments = explode($separator, $data);
         $this->head['header_found'] = true;
         foreach ($dataSegments as $dataSegmentIndex => $dataSegment) {
             // Check for a segment that seems to contain HTTP-headers
             if (preg_match('/(Set-Cookie|Content-Type|Transfer-Encoding):/', $dataSegment)) {
                 // Get this segment
                 $this->head['headers'] = trim($dataSegment);
                 // Use the remaining segments for the body
                 unset($dataSegments[$dataSegmentIndex]);
                 $this->body = implode("\r\n", $dataSegments);
                 break;
             }
             // Only allow for a body after a header (and ignore double headers)
             unset($dataSegments[$dataSegmentIndex]);
         }
     }
     // Exit when no proper headers have been found
     if ($this->head['header_found'] == false) {
         $this->debug->warning('CURL contains no HTTP headers');
         return null;
     }
     if (empty($this->head['http_code'])) {
         $this->head['http_code'] = 200;
     }
     // Statistics
     $this->debug->profiler('CURL total time: ' . round(curl_getinfo($handle, CURLINFO_TOTAL_TIME), 4) . ' seconds');
     $this->debug->profiler('CURL connect time: ' . round(curl_getinfo($handle, CURLINFO_CONNECT_TIME), 4) . ' seconds');
     $this->debug->profiler('CURL DNS-time: ' . round(curl_getinfo($handle, CURLINFO_NAMELOOKUP_TIME), 4) . ' seconds');
     $this->debug->profiler('CURL download speed: ' . round(curl_getinfo($handle, CURLINFO_SPEED_DOWNLOAD * 8 / 1024), 4) . ' Kb/s');
     //$this->debug->trace( "CURL information", curl_getinfo($handle));
     //$this->debug->trace( "HTTP headers", $this->head );
     //$this->debug->trace( "HTTP body", $this->body );
     // Handle MageBridge HTTP-messaging
     if (preg_match_all('/X-MageBridge-(Notice|Error|Warning): ([^\\s]+)/', $this->head['headers'], $matches)) {
         foreach ($matches[0] as $index => $match) {
             $type = $matches[1][$index];
             $message = $matches[2][$index];
             if (!empty($type) && !empty($message)) {
                 $message = base64_decode($message);
                 $this->app->enqueueMessage($message, $type);
             }
         }
     }
     // Process the X-MageBridge-Customer header
     if ($this->getHeader('X-MageBridge-Customer') != null) {
         $value = $this->getHeader('X-MageBridge-Customer');
         MageBridgeModelBridge::getInstance()->addSessionData('customer/email', $value);
         MageBridgeModelUser::getInstance()->postlogin($value, null, true, true);
     }
     // Process the X-MageBridge-Form-Key header
     if ($this->getHeader('X-MageBridge-Form-Key') != null) {
         $value = $this->getHeader('X-MageBridge-Form-Key');
         MageBridgeModelBridge::getInstance()->addSessionData('form_key', $value);
     }
     // Log other Status Codes than 200
     if ($this->head['http_code'] != 200) {
         if ($this->head['http_code'] == 500) {
             $this->debug->error('CURL received HTTP status ' . $this->head['http_code']);
         } else {
             $this->debug->warning('CURL received HTTP status ' . $this->head['http_code']);
         }
     }
     // If we receive status 0, log it
     if ($this->head['http_code'] == 0) {
         $this->head['http_error'] = curl_error($handle);
         $this->debug->trace('CURL error', curl_error($handle));
     }
     // If we receive an exception, exit the bridge
     if ($this->head['http_code'] == 0 || $this->head['http_code'] == 500) {
         $this->init = self::CONNECTION_ERROR;
         $this->state = 'INTERNAL ERROR';
         curl_close($handle);
         return $this->body;
     }
     // If we receive a 404, log it
     if ($this->head['http_code'] == 404) {
         $this->init = self::CONNECTION_ERROR;
         $this->state = '404 NOT FOUND';
         curl_close($handle);
         if ($this->app->isSite() == 1 && MagebridgeModelConfig::load('enable_notfound') == 1) {
             JError::raiseError(404, JText::_('Page Not Found'));
             return null;
         } else {
             header('HTTP/1.0 404 Not Found');
             return $this->body;
         }
     }
     // If we have an empty body, log it
     if (empty($this->body)) {
         $this->debug->warning('CURL received empty body');
         if (!empty($this->head['headers'])) {
             $this->debug->trace('CURL headers', $this->head['headers']);
         }
     }
     // Define which cookies to spoof
     $cookies = MageBridgeBridgeHelper::getBridgableCookies();
     $defaultSessionName = ini_get('session.name');
     if (empty($defaultSessionName)) {
         $defaultSessionName = 'PHPSESSID';
     }
     $cookies[] = $defaultSessionName;
     // Add the default session for sake of badly written Magento extensions
     // Handle cookies
     if (MagebridgeModelConfig::load('bridge_cookie_all') == 1) {
         preg_match_all('/Set-Cookie: ([a-zA-Z0-9\\-\\_\\.]+)\\=(.*)/', $this->head['headers'], $matches);
     } else {
         preg_match_all('/Set-Cookie: (' . implode('|', $cookies) . ')\\=(.*)/', $this->head['headers'], $matches);
     }
     // Loop through the matches
     if (!empty($matches)) {
         $matchedCookies = array();
         foreach ($matches[0] as $index => $match) {
             // Extract the cookie-information
             $cookieName = $matches[1][$index];
             $cookieValue = $matches[2][$index];
             // Strip the meta-data from the cookie
             if (preg_match('/^([^\\;]+)\\;(.*)/', $cookieValue, $cookieValueMatch)) {
                 $cookieValue = $cookieValueMatch[1];
             }
             // Trim the cookie
             $cookieValue = trim($cookieValue);
             // Check if the cookie was dealt with or not
             if (in_array($cookieName, $matchedCookies)) {
                 continue;
             } else {
                 $matchedCookies[] = $cookieName;
             }
             // Set the cookie
             if (!headers_sent()) {
                 if ($cookieName == 'persistent_shopping_cart' && isset($matches[3][$index]) && preg_match('/expires=([^\\;]+)/', $matches[3][$index], $paramsMatch)) {
                     $expires = strtotime($paramsMatch[1]);
                 } else {
                     $expires = 0;
                 }
                 setcookie($cookieName, $cookieValue, $expires, '/', '.' . JURI::getInstance()->toString(array('host')));
                 $_COOKIE[$cookieName] = $cookieValue;
             }
             // Store this cookie also in the default Joomal! session (in case extra cookies are disabled)
             $session = JFactory::getSession();
             $session->set('magebridge.cookie.' . $cookieName, $cookieValue);
         }
     }
     // Handle the extra remember-me cookie
     $user = JFactory::getUser();
     if ($user->id > 0 && !empty($_COOKIE['persistent_shopping_cart'])) {
         $password = $user->password_clear;
         if (empty($password)) {
             $password = $this->input->getString('password');
         }
         if (empty($password)) {
             $password = $user->password;
         }
         if (!empty($password)) {
             $credentials = array('username' => $user->username, 'password' => $password);
             // Create the encryption key, apply extra hardening using the user agent string.
             $privateKey = JApplication::getHash(@$_SERVER['HTTP_USER_AGENT']);
             $key = new JCryptKey('simple', $privateKey, $privateKey);
             $crypt = new JCrypt(new JCryptCipherSimple(), $key);
             $rcookie = $crypt->encrypt(serialize($credentials));
             $lifetime = time() + 365 * 24 * 60 * 60;
             // Use domain and path set in config for cookie if it exists.
             $cookie_domain = JFactory::getConfig()->get('cookie_domain', '');
             $cookie_path = JFactory::getConfig()->get('cookie_path', '/');
             setcookie(JApplication::getHash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain);
         }
     }
     // Handle redirects
     preg_match('/^Location: ([^\\s]+)/m', $this->head['headers'], $matches);
     if ($this->allow_redirects && (preg_match('/^3([0-9]+)/', $this->head['http_code']) || !empty($matches))) {
         $originalLocation = trim(array_pop($matches));
         $location = $originalLocation;
         // Check for a location-override
         if ($this->getHeader('X-MageBridge-Location') != null) {
             // But only override the location, if there is no error present
             if (strstr($location, 'startcustomization=1') == false) {
                 $this->debug->notice('X-MageBridge-Location = ' . $this->getHeader('X-MageBridge-Location'));
                 $location = $this->getHeader('X-MageBridge-Location');
             }
         }
         // Check for a location-override if the customer is logged in
         if ($this->getHeader('X-MageBridge-Location-Customer') != null && $this->getHeader('X-MageBridge-Customer') != null) {
             MageBridgeModelUser::getInstance()->postlogin($this->getHeader('X-MageBridge-Customer'), null, true, true);
             $this->debug->notice('X-MageBridge-Location-Customer = ' . $this->getHeader('X-MageBridge-Location-Customer'));
             $location = $this->getHeader('X-MageBridge-Location-Customer');
         }
         // Check for the location in the CURL-information
         if (empty($location) && isset($this->head['info']['redirect_url'])) {
             $location = $this->head['info']['redirect_url'];
         }
         // No location could be found
         if (empty($location)) {
             $this->debug->trace('Redirect requested but no URL found', $this->head['headers']);
             return false;
         }
         // Check if the current location is the Magento homepage, and if so, override it with the Joomla!-stored referer instead
         $referer = $this->bridge->getHttpReferer();
         if ($location == $this->bridge->getJoomlaBridgeUrl()) {
             if (MagebridgeModelConfig::load('use_homepage_for_homepage_redirects') == 1) {
                 $location = JURI::base();
             } elseif (MagebridgeModelConfig::load('use_referer_for_homepage_redirects') == 1 && !empty($referer) && $referer != JURI::current()) {
                 $location = $referer;
             }
         }
         //$location = preg_replace('/magebridge\.php\//', '', $location);
         $this->debug->warning('Trying to redirect to new location ' . $location);
         header('X-MageBridge-Redirect: ' . $originalLocation);
         $this->setRedirect($location);
     }
     curl_close($handle);
     return $this->body;
 }
 public static function getUserData()
 {
     return MageBridgeModelUser::getInstance()->getRequestData();
 }