function onUserLoginFailure($response) { jimport('joomla.error.log'); $log = JLog::getInstance(); $errorlog = array(); switch ($response['status']) { case JAUTHENTICATE_STATUS_CANCEL: $errorlog['status'] = $response['type'] . " CANCELED: "; $errorlog['comment'] = $response['error_message']; $log->addEntry($errorlog); break; case JAUTHENTICATE_STATUS_FAILURE: $errorlog['status'] = $response['type'] . " FAILURE: "; if ($this->params->get('log_username', 0)) { $errorlog['comment'] = $response['error_message'] . ' ("' . $response['username'] . '")'; } else { $errorlog['comment'] = $response['error_message']; } $log->addEntry($errorlog); break; default: $errorlog['status'] = $response['type'] . " UNKNOWN ERROR: "; $errorlog['comment'] = $response['error_message']; $log->addEntry($errorlog); break; } }
/** * Checks to see if the payerID matches a previous payerID in the virtuemart DB * We only care about the Username for Joomla, but the password is really the payerID * That is passed from Virtuemart. The payerID is then used to check the ID from * Joomla with the ID in the Virtuemart user_info. We do this just to make sure it is * The correct user trying to login and not someone else * * @access public * @param string $username Username for authentication * @param string $password Password for authentication * @param object $response Authentication response object * @return boolean * @since 1.5 */ function onAuthenticate($credentials, $options, &$response) { $db =& JFactory::getDBO(); $query = 'SELECT * FROM `#__users` WHERE username='******'username']); $db->setQuery($query); $result = $db->loadObject(); $options = array('format' => "{DATE}\t{TIME}\t{USER_ID}\t{COMMENT}"); $log =& JLog::getInstance(); if (!$result) { $response->status = JAUTHENTICATE_STATUS_FAILURE; $response->error_message = 'User does not exist'; $log->addEntry(array('comment' => 'User does not exist')); } else { $log->addEntry(array('comment' => 'Found User')); $query = 'SELECT * FROM `#__vm_user_info` WHERE extra_field_3 =' . $db->Quote($credentials['password']) . ' AND user_id =' . $db->Quote($result->id) . ' ORDER by mdate DESC'; $db->setQuery($query); $result2 = $db->loadObject(); //Check to see if we found a user with the User Id and Payer Id match //If so login the user and if not do not login. if (!$result2) { $log->addEntry(array('comment' => 'No user found with Payer ID in Virtuemart')); $response->status = JAUTHENTICATE_STATUS_FAILURE; $response->error_message = 'No user found with Payer ID in Virtuemart'; } else { $log->addEntry(array('comment' => 'User Found Logging in...')); $response->email = $result->email; $response->status = JAUTHENTICATE_STATUS_SUCCESS; } } }
public function log() { $trace = ""; foreach ($this->trace as $v) { $trace .= "===================================\n"; $trace .= "FILE:" . $v['file'] . "\n"; $trace .= "LINE:" . $v['line'] . "\n"; $trace .= "CLASS:" . $v['class'] . "\n"; $trace .= "FUNCTION:" . $v['function'] . "\n"; // $trace .="ARGS:" . var_export($v['args'], true) . "\n"; $trace .= "====================================\n"; } $message = "*****************************************\n"; $message = "\nFILE : " . $this->getFile() . "\n"; $message .= "LINE : " . $this->getLine() . "\n"; $message .= "CODE : " . $this->getCode() . "\n"; $message .= "MESSAGE : " . $this->getMessage() . "\n"; if ($this->data) { $message .= "EXTRA INFO : " . $this->data . "\n"; } if ($trace) { $message .= "TRACE : " . $trace . "\n"; } $message = "*****************************************\n"; // get an instance of JLog for myerrors log file $log = JLog::getInstance(); $entry = new JLogEntry($message, JLog::ALERT); $log->add($entry); }
public function log($message) { // get an instance of JLog for myerrors log file $log = JLog::getInstance(); $entry = new JLogEntry($message, JLog::ALERT); $log->add($entry); }
/** * A method that make a long url to short url * * @param string $link * @param array $params * @return string */ public static function getShortUrl($link, $params){ JLoader::register("ItpShortUrlSocialButtons",JPATH_PLUGINS.DS."content".DS."itpsocialbuttons".DS."itpshorturlsocialbuttons.php"); $options = array( "login" => $params->get("login"), "apiKey" => $params->get("apiKey"), "service" => $params->get("shortUrlService"), ); $shortUrl = new ItpShortUrlSocialButtons($link,$options); $shortLink = $shortUrl->getUrl(); if(!$shortLink) { jimport( 'joomla.error.log' ); // get an instance of JLog for myerrors log file $log = JLog::getInstance(); // create entry array $entry = array( 'LEVEL' => '1', 'STATUS' => "ITPSocialButtons", 'COMMENT' => $shortUrl->getError() ); // add entry to the log $log->addEntry($entry); } else { $link = $shortLink; } return $link; }
function Storelog($name, $logdata) { jimport('joomla.error.log'); $options = array('format' => "{DATE}\t{TIME}\t{USER}\t{DESC}"); $path = dirname(__FILE__); $my =& JFactory::getUser(); $logs =& JLog::getInstance($logdata['JT_CLIENT'] . '_' . $name . '.log', $options, $path); $logs->addEntry(array('user' => $my->name . '(' . $my->id . ')', 'desc' => json_encode($logdata['raw_data']))); }
function writeEntry($log_array = array(), $filename = 'joomlalms_error_log.txt', $format = 'Date: {DATE} {TIME} {COMMENT}') { jimport('joomla.error.log'); $log =& JLog::getInstance($filename, array('format' => $format)); $log_array[] = '###########################################################################'; $log_text = "\n" . implode("\n", $log_array) . "\n"; $status = $log->addEntry(array('COMMENT' => $log_text)); return $status; }
function hellodefault() { //get text string based on languages $ret = JText::_('hellodefault'); //log information jimport('joomla.utilities.log'); $log =& JLog::getInstance(); $log->addEntry(array("level" => 0, "status" => 1, "comment" => "hellodefault :" . $ret)); //print string echo $ret; }
public function getData() { if (!isset($this->data)) { $query = "SELECT name, username, email, id FROM #__users"; $this->data = $this->_getList($query); } jimport('joomla.error.log'); $log = JLog::getInstance('first_user.php'); $entry = array('LEVEL' => 1, 'STATUS' => 'First username: '******'COMMENT' => $this->data[0]->username); $log->addEntry($entry); return $this->data; }
function Storelog($name, $logdata) { jimport('joomla.error.log'); $options = array('format' => "{DATE}\t{TIME}\t{USER}\t{DESC}"); if (JVERSION >= '1.6.0') { $path = JPATH_SITE . '/plugins/payment/' . $name . '/' . $name . '/'; } else { $path = JPATH_SITE . '/plugins/payment/' . $name . '/'; } $my = JFactory::getUser(); $logs = JLog::getInstance($logdata['JT_CLIENT'] . '_' . $name . '.log', $options, $path); $logs->addEntry(array('user' => $my->name . '(' . $my->id . ')', 'desc' => json_encode($logdata['raw_data']))); }
function log($msg) { global $linkr_debug; if (empty($msg) || !$linkr_debug['debug']) { return; } static $log; if (is_null($log)) { jimport('joomla.error.log'); $o = array('format' => '{DATE} {TIME} ({C-IP}), {COMMENT}'); $log =& JLog::getInstance('linkr.php', $o); } $log->addEntry(array('comment' => $msg)); }
/** * Ritorna un array di righe. * * @param string $where * @param string $orderby * @return array Array di risultati */ public function getItemsByCategoria($where = 'pubblicato=1', $orderby = 'datapubblicazione DESC') { try { if (empty($this->_items)) { $this->_items = $this->_getList($this->_build_query($where, $orderby), $this->getState('limitstart'), $this->getState('limit')); if ($this->_dbg) $this->_japp->enqueueMessage('Fetched rows :' . count($this->_items)); } return $this->_items; } catch (Exception $e) { jimport('joomla.error.log'); $log = &JLog::getInstance('com_gglms.log.php'); $log->addEntry(array('comment' => $e->getMessage(), 'status' => $e->getCopde)); if ($this->_dbg) $this->_japp->enqueueMessage($e->getMessage(), 'error'); $this->_content = array(); } }
protected function __construct() { $this->_log =& JLog::getInstance('db.error.php'); $conf =& JFactory::getConfig(); $host = $conf->getValue('config.oracleHost'); $port = $conf->getValue('config.oraclePort'); $service = $conf->getValue('config.oracleServiceName'); $db_username = $conf->getValue('config.oracleUser'); $db_password = $conf->getValue('config.oraclePassword'); $tns = "\n\t\t\t(DESCRIPTION =\n\t\t\t\t(ADDRESS_LIST =\n\t\t\t\t\t(ADDRESS = (PROTOCOL = TCP)(HOST = {$host})(PORT = {$port}))\n\t\t\t\t)\n\t\t\t\t(CONNECT_DATA =\n\t\t\t\t\t(SERVICE_NAME = {$service})\n\t\t\t\t)\n\t\t\t)\n\t\t\t"; try { $this->_pdo = new PDO("oci:dbname=" . $tns . ";charset=TR8MSWIN1254", $db_username, $db_password); // hatalar� g�rmek i�in a�a��daki sat�r� uncomment yap $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); } catch (Exception $e) { $this->log($e->getMessage()); print_r("Oracle'a bağlanılamadı: " . $e->getMessage()); exit; } }
function onLoginFailure($response) { jimport('joomla.error.log'); $log = JLog::getInstance(); $errorlog = array(); switch ($response['status']) { case JAUTHENTICATE_STATUS_CANCEL: $errorlog['status'] = $response['type'] . " CANCELED: "; $errorlog['comment'] = $response['error_message']; $log->addEntry($errorlog); break; case JAUTHENTICATE_STATUS_FAILURE: $errorlog['status'] = $response['type'] . " FAILURE: "; $errorlog['comment'] = $response['error_message']; $log->addEntry($errorlog); break; default: $errorlog['status'] = $response['type'] . " UNKNOWN ERROR: "; $errorlog['comment'] = $response['error_message']; $log->addEntry($errorlog); break; } }
function start_upload() { $mainframe =& JFactory::getApplication(); $file = JRequest::getVar('Filedata', '', 'files', 'array'); $folder = JPATH_ADMINISTRATOR . DS . 'components/com_joomailermailchimpintegration/templates/'; $format = JRequest::getVar('format', 'html', '', 'cmd'); $return = JRequest::getVar('return-url', null, 'post', 'base64'); $err = null; // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe jimport('joomla.filesystem.file'); $file['name'] = JFile::makeSafe($file['name']); if (isset($file['name'])) { $filepath = JPath::clean($folder . DS . strtolower($file['name'])); if (!$this->canUpload($file, $err)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err)); header('HTTP/1.0 415 Unsupported Media Type'); jexit('Error. Unsupported Media Type!'); } else { JError::raiseNotice(100, JText::_($err)); if ($return) { $mainframe->redirect(base64_decode($return)); } return; } } if (JFile::exists($filepath)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'File already exists: ' . $filepath)); header('HTTP/1.0 409 Conflict'); jexit('Error. File already exists'); } else { JError::raiseNotice(100, JText::_('Error. File already exists')); if ($return) { $mainframe->redirect(base64_decode($return)); } return; } } if (!JFile::upload($file['tmp_name'], $filepath)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'Cannot upload: ' . $filepath)); header('HTTP/1.0 400 Bad Request'); jexit('Error. Unable to upload file'); } else { JError::raiseWarning(100, JText::_('Error. Unable to upload file')); if ($return) { $mainframe->redirect(base64_decode($return)); } return; } } else { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance(); $log->addEntry(array('comment' => $folder)); jexit(JText::_('JM_UPLOAD_COMPLETE')); } else { if ($this->unzip($folder, strtolower($file['name']))) { $msg = JText::_('JM_UPLOAD_COMPLETE'); } else { $msg = JText::_('Error. Unable to upload file'); } } } } else { $mainframe->redirect('index.php', 'Invalid Request', 'error'); } $link = 'index.php?option=com_joomailermailchimpintegration&view=templates'; $this->setRedirect($link, $msg); }
/** * Logs an error * * @param mixed $response * * @return void */ protected function _logError($response) { $log = JLog::getInstance('system_log.php'); $message = "\nerror_message=" . $response->message() . "\n"; if ($response->cvv_result()) { $message .= "cvv_result=" . implode(" ", $response->cvv_result()->toArray()) . "\n"; } if ($response->avs_result()) { $message .= "avs_result=" . implode(" ", $response->avs_result()->toArray()) . "\n"; } if ($response->params()) { $message .= "params=" . implode(" ", $response->params()) . "\n"; } $log->addEntry(array('comment' => $message, 'level' => 'ERROR')); }
/** * Initializes the options for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param object An optional KConfig object with configuration options. * @return void */ protected function _initialize(KConfig $config) { $log = JLog::getInstance('system_log.php'); $config->append(array('log' => $log)); parent::_initialize($config); }
/** * Log error handler * Logs the error message to a system log file * * @param object &$error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated 12.1 * @see raise() * @since 11.1 */ public static function handleLog(&$error, $options) { // Deprecation warning. JLog::add('JError::handleLog() is deprecated.', JLog::WARNING, 'deprecated'); static $log; if ($log == null) { $fileName = date('Y-m-d') . '.error.log'; $options['format'] = "{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}"; $log = JLog::getInstance($fileName, $options); } $entry['level'] = $error->get('level'); $entry['code'] = $error->get('code'); $entry['message'] = str_replace(array("\r", "\n"), array('', '\\n'), $error->get('message')); $log->addEntry($entry); return $error; }
/** * Upload a file * * @since 1.5 */ function upload() { global $mainframe; // Check for request forgeries JRequest::checkToken('request') or jexit('Invalid Token'); $file = JRequest::getVar('Filedata', '', 'files', 'array'); $folder = JRequest::getVar('folder', '', '', 'path'); $format = JRequest::getVar('format', 'html', '', 'cmd'); $return = JRequest::getVar('return-url', null, 'post', 'base64'); $err = null; // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe jimport('joomla.filesystem.file'); $file['name'] = JFile::makeSafe($file['name']); if (isset($file['name'])) { $filepath = JPath::clean(COM_MEDIA_BASE . DS . $folder . DS . strtolower($file['name'])); if (!MediaHelper::canUpload($file, $err)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err)); header('HTTP/1.0 415 Unsupported Media Type'); jexit('Error. Unsupported Media Type!'); } else { JError::raiseNotice(100, JText::_($err)); // REDIRECT if ($return) { $mainframe->redirect(base64_decode($return) . '&folder=' . $folder); } return; } } if (JFile::exists($filepath)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'File already exists: ' . $filepath)); header('HTTP/1.0 409 Conflict'); jexit('Error. File already exists'); } else { JError::raiseNotice(100, JText::_('Error. File already exists')); // REDIRECT if ($return) { $mainframe->redirect(base64_decode($return) . '&folder=' . $folder); } return; } } if (!JFile::upload($file['tmp_name'], $filepath)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'Cannot upload: ' . $filepath)); header('HTTP/1.0 400 Bad Request'); jexit('Error. Unable to upload file'); } else { JError::raiseWarning(100, JText::_('Error. Unable to upload file')); // REDIRECT if ($return) { $mainframe->redirect(base64_decode($return) . '&folder=' . $folder); } return; } } else { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance(); $log->addEntry(array('comment' => $folder)); jexit('Upload complete'); } else { $mainframe->enqueueMessage(JText::_('Upload complete')); // REDIRECT if ($return) { $mainframe->redirect(base64_decode($return) . '&folder=' . $folder); } return; } } } else { $mainframe->redirect('index.php', 'Invalid Request', 'error'); } }
/** * Log error handler * Logs the error message to a system log file * * @param object $error Exception object to handle * @param array $options Handler options * * @return object The exception object * * @deprecated * @see raise() * @since 11.1 */ public static function handleLog(&$error, $options) { static $log; if ($log == null) { jimport('joomla.error.log'); $fileName = date('Y-m-d') . '.error.log'; $options['format'] = "{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}"; $log = JLog::getInstance($fileName, $options); } $entry['level'] = $error->get('level'); $entry['code'] = $error->get('code'); $entry['message'] = str_replace(array("\r", "\n"), array('', '\\n'), $error->get('message')); $log->addEntry($entry); return $error; }
function log($msg) { jimport('joomla.error.log'); $log = JLog::getInstance('updates.txt'); $log->addEntry(array('comment' => 'LOG: ' . $msg)); }
function log($type, $message, $code = null) { $log =& JLog::getInstance('com_jucene.log.php'); $log->addEntry(array('LEVEL' => $type, 'COMMENT' => $message)); }
function uploadranks() { $kunena_config = KunenaFactory::getConfig(); $kunena_app =& JFactory::getApplication(); // load language fo component media JPlugin::loadLanguage('com_media'); $params =& JComponentHelper::getParams('com_media'); require_once JPATH_ADMINISTRATOR . '/components/com_media/helpers/media.php'; define('COM_KUNENA_MEDIA_BASE', JPATH_ROOT . '/components/com_kunena/template/' . $kunena_config->template . '/images'); // Check for request forgeries JRequest::checkToken('request') or jexit('Invalid Token'); $file = JRequest::getVar('Filedata', '', 'files', 'array'); $folderranks = JRequest::getVar('folderranks', 'ranks', '', 'path'); $format = JRequest::getVar('format', 'html', '', 'cmd'); $return = JRequest::getVar('return-url', null, 'post', 'base64'); $err = null; // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe jimport('joomla.filesystem.file'); $file['name'] = JFile::makeSafe($file['name']); if (isset($file['name'])) { $filepathranks = JPath::clean(COM_KUNENA_MEDIA_BASE . '/' . $folderranks . '/' . strtolower($file['name'])); if (!MediaHelper::canUpload($file, $err)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'Invalid: ' . $filepathranks . ': ' . $err)); header('HTTP/1.0 415 Unsupported Media Type'); jexit('Error. Unsupported Media Type!'); } else { JError::raiseNotice(100, JText::_($err)); // REDIRECT if ($return) { while (@ob_end_clean()) { } $kunena_app->redirect(base64_decode($return)); } return; } } if (JFile::exists($filepathranks)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'File already exists: ' . $filepathranks)); header('HTTP/1.0 409 Conflict'); jexit('Error. File already exists'); } else { JError::raiseNotice(100, JText::_('COM_KUNENA_A_RANKS_UPLOAD_ERROR_EXIST')); // REDIRECT if ($return) { while (@ob_end_clean()) { } $kunena_app->redirect(base64_decode($return)); } return; } } if (!JFile::upload($file['tmp_name'], $filepathranks)) { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance('upload.error.php'); $log->addEntry(array('comment' => 'Cannot upload: ' . $filepathranks)); header('HTTP/1.0 400 Bad Request'); jexit('Error. Unable to upload file'); } else { JError::raiseWarning(100, JText::_('COM_KUNENA_A_RANKS_UPLOAD_ERROR_UNABLE')); // REDIRECT if ($return) { while (@ob_end_clean()) { } $kunena_app->redirect(base64_decode($return)); } return; } } else { if ($format == 'json') { jimport('joomla.error.log'); $log =& JLog::getInstance(); $log->addEntry(array('comment' => $filepathranks)); jexit('Upload complete'); } else { $kunena_app->enqueueMessage(JText::_('COM_KUNENA_A_RANKS_UPLOAD_SUCCESS')); // REDIRECT if ($return) { while (@ob_end_clean()) { } $kunena_app->redirect(base64_decode($return)); } return; } } } else { while (@ob_end_clean()) { } $kunena_app->redirect('index.php', 'Invalid Request', 'error'); } }
/** * Logic to import csv files with content item data * * @access public * @return void * @since 1.5 */ function importcsv() { // Check for request forgeries if (JRequest::getCmd('task') != 'importcsv') { JRequest::checkToken() or jexit('Invalid Token'); echo '<link rel="stylesheet" href="' . JURI::base() . 'components/com_flexicontent/assets/css/flexicontentbackend.css" />'; if (FLEXI_J30GE) { $fc_css = JURI::base() . 'components/com_flexicontent/assets/css/j3x.css'; } else { if (FLEXI_J16GE) { $fc_css = JURI::base() . 'components/com_flexicontent/assets/css/j25.css'; } else { $fc_css = JURI::base() . 'components/com_flexicontent/assets/css/j15.css'; } } echo '<link rel="stylesheet" href="' . $fc_css . '" />'; } else { // output this before every other output echo 'success||||' . (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) . '||||'; } // Get item model $model = $this->getModel('item'); // Set some variables $link = 'index.php?option=com_flexicontent&view=import'; // $_SERVER['HTTP_REFERER']; $task = JRequest::getCmd('task'); $app = JFactory::getApplication(); $db = JFactory::getDBO(); $user = JFactory::getUser(); $session = JFactory::getSession(); $has_zlib = version_compare(PHP_VERSION, '5.4.0', '>='); $parse_log = "\n\n\n" . '<b>please click</b> <a href="JavaScript:window.history.back();">here</a> to return previous page' . "\n\n\n"; $log_filename = 'importcsv_' . $user->id . '.php'; if (FLEXI_J16GE) { jimport('joomla.log.log'); JLog::addLogger(array('text_file' => $log_filename)); } else { jimport('joomla.error.log'); $log = JLog::getInstance($log_filename); } // RESET/CLEAR an already started import task, e.g. import process was interrupted for some reason if ($task == 'clearcsv') { // Clear any import data from session $conf = $has_zlib ? base64_encode(zlib_encode(serialize(null), -15)) : base64_encode(serialize(null)); $session->set('csvimport_config', $conf, 'flexicontent'); $session->set('csvimport_lineno', 0, 'flexicontent'); // Set a total results message and redirect $app->enqueueMessage('Imported task cleared', 'notice'); $this->setRedirect($link); return; } else { if ($task == 'importcsv') { $conf = $session->get('csvimport_config', "", 'flexicontent'); $conf = unserialize($conf ? $has_zlib ? zlib_decode(base64_decode($conf)) : base64_decode($conf) : ""); $lineno = $session->get('csvimport_lineno', 999999, 'flexicontent'); if (empty($conf)) { $app->enqueueMessage('Can not continue import, import task not initialized or already finished:', 'warning'); $this->setRedirect($link); return; } } else { if ($task == 'initcsv' || $task == 'testcsv') { $conf = array(); $conf['failure_count'] = $conf['success_count'] = 0; // Retrieve basic configuration $conf['debug'] = JRequest::getInt('debug', 0); $conf['import_items_per_step'] = JRequest::getInt('import_items_per_step', 5); if ($conf['import_items_per_step'] > 50) { $conf['import_items_per_step'] = 50; } if (!$conf['import_items_per_step']) { $conf['import_items_per_step'] = 5; } // Retrieve from configuration for (a) typeid, language, main category, secondaries categories, etc $conf['type_id'] = JRequest::getInt('type_id', 0); $conf['id_col'] = JRequest::getInt('id_col', 0); $conf['language'] = JRequest::getVar('language', ''); $conf['state'] = JRequest::getVar('state', ''); $conf['maincat'] = JRequest::getInt('maincat', 0); $conf['maincat_col'] = JRequest::getInt('maincat_col', 0); $conf['seccats'] = JRequest::getVar('seccats', array(), 'post', 'array'); $conf['seccats_col'] = JRequest::getInt('seccats_col', 0); $conf['tags_col'] = JRequest::getInt('tags_col', 0); $conf['created_col'] = JRequest::getInt('created_col', 0); $conf['created_by_col'] = JRequest::getInt('created_by_col', 0); $conf['modified_col'] = JRequest::getInt('modified_col', 0); $conf['modified_by_col'] = JRequest::getInt('modified_by_col', 0); $conf['metadesc_col'] = JRequest::getInt('metadesc_col', 0); $conf['metakey_col'] = JRequest::getInt('metakey_col', 0); $conf['publish_up_col'] = JRequest::getInt('publish_up_col', 0); $conf['publish_down_col'] = JRequest::getInt('publish_down_col', 0); $conf['ignore_unused_cols'] = JRequest::getInt('ignore_unused_cols', 0); // ******************************************************************************************** // Obligatory form fields, js validation should have prevented form submission but check anyway // ******************************************************************************************** if (!$conf['type_id']) { // Check for the required Content Type Id echo "<script>alert ('Please select Content Type for the imported items');"; echo "window.history.back();"; echo "</script>"; jexit(); } if (!$conf['maincat'] && !$conf['maincat_col']) { // Check for the required main category echo "<script>alert ('Please select main category for the imported items');"; echo "window.history.back();"; echo "</script>"; jexit(); } // ****************************************************************************************************** // Retrieve CSV file format variables, EXPANDING the Escape Characters like '\n' ... provided by the form // ****************************************************************************************************** $pattern = '/(?<!\\\\)(\\\\(?:n|r|t|v|f|[0-7]{1,3}|x[0-9a-f]{1,2}))/i'; $replace = 'eval(\'return "$1";\')'; $conf['field_separator'] = preg_replace_callback($pattern, function ($matches) { $r = $matches[1]; eval("\$r = \"{$r}\";"); return $r; }, JRequest::getVar('field_separator')); $conf['enclosure_char'] = preg_replace_callback($pattern, function ($matches) { $r = $matches[1]; eval("\$r = \"{$r}\";"); return $r; }, JRequest::getVar('enclosure_char')); $conf['record_separator'] = preg_replace_callback($pattern, function ($matches) { $r = $matches[1]; eval("\$r = \"{$r}\";"); return $r; }, JRequest::getVar('record_separator')); // **************************************************************************************************************** // Check for proper CSV file format variables, js validation should have prevented form submission but check anyway // **************************************************************************************************************** if ($conf['field_separator'] == '' || $conf['record_separator'] == '') { // Check for the (required) title column echo "<script>alert ('CSV format not valid, please enter Field Separator and Item Separator');"; echo "window.history.back();"; echo "</script>"; jexit(); } // Retrieve the uploaded CSV file $csvfile = @$_FILES["csvfile"]["tmp_name"]; if (!is_file($csvfile)) { echo "<script>alert ('Upload file error!');"; echo "window.history.back();"; echo "</script>"; jexit(); } // **************************************************** // Read & Parse the CSV file according the given format // **************************************************** $contents = FLEXIUtilities::csvstring_to_array(file_get_contents($csvfile), $conf['field_separator'], $conf['enclosure_char'], $conf['record_separator']); // Basic error checking, for empty data if (!$contents || count($contents[0]) <= 0) { echo "<script>alert ('Upload file error! CSV file format is not correct!');"; echo "window.history.back();"; echo "</script>"; jexit(); } // ******************************************************************************** // Get field names (from the header line (row 0), and remove it form the data array // ******************************************************************************** $conf['columns'] = flexicontent_html::arrayTrim($contents[0]); unset($contents[0]); $q = 'SELECT id, name, field_type, label FROM #__flexicontent_fields AS fi' . ' JOIN #__flexicontent_fields_type_relations AS ftrel ON ftrel.field_id = fi.id AND ftrel.type_id=' . $conf['type_id']; $db->setQuery($q); $conf['thefields'] = $db->loadObjectList('name'); unset($conf['thefields']['tags']); // Prevent Automated Raw insertion of tags, we will use special code // ****************************************************************** // Check for REQUIRED columns and decide CORE property columns to use // ****************************************************************** $core_props = array(); if ($conf['id_col'] && !in_array('id', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'id\\' (Item ID)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['id_col']) { $core_props['id'] = 'Item ID'; } } if (!in_array('title', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'title\\'');"; echo "window.history.back();"; echo "</script>"; jexit(); } $core_props['title'] = 'Title (core)'; $core_props['text'] = 'Description (core)'; $core_props['alias'] = 'Alias (core)'; if (!$conf['language'] && !in_array('language', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'language\\'');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if (!$conf['language']) { $core_props['language'] = 'Language'; } } if (!strlen($conf['state']) && !in_array('state', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'state\\'');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if (!strlen($conf['state'])) { $core_props['state'] = 'State'; } } if ($conf['maincat_col'] && !in_array('catid', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'catid\\' (primary category)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['maincat_col']) { $core_props['catid'] = 'Primary category'; } } if ($conf['seccats_col'] && !in_array('cid', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'cid\\' (secondary categories)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['seccats_col']) { $core_props['cid'] = 'Secondary categories'; } } if ($conf['created_col'] && !in_array('created', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'created\\' (Creation date)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['created_col']) { $core_props['created'] = 'Creation Date'; } } if ($conf['created_by_col'] && !in_array('created_by', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'created_by\\' (Creator - Author)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['created_by_col']) { $core_props['created_by'] = 'Creator (Author)'; } } if ($conf['modified_col'] && !in_array('modified', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'modified\\' (Modification date)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['modified_col']) { $core_props['modified'] = 'Modification Date'; } } if ($conf['modified_by_col'] && !in_array('modified_by', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'modified_by\\' (Last modifier)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['modified_by_col']) { $core_props['modified_by'] = 'Last modifier'; } } if ($conf['metadesc_col'] && !in_array('metadesc', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'metadesc\\' (META Description)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['metadesc_col']) { $core_props['metadesc'] = 'Creator - Author'; } } if ($conf['metakey_col'] && !in_array('metakey', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'metakey\\' (META Keywords)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['metakey_col']) { $core_props['metakey'] = 'META Keywords'; } } if ($conf['publish_up_col'] && !in_array('publish_up', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'publish_up\\' (Start publication date)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['publish_up_col']) { $core_props['publish_up'] = 'Start publication date'; } } if ($conf['publish_down_col'] && !in_array('publish_down', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'publish_down\\' (End publication Date)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['publish_down_col']) { $core_props['publish_down'] = 'End publication Date'; } } if ($conf['tags_col'] == 1 && !in_array('tags_names', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'tags_names\\' (Comma separated list of tag names)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['tags_col'] == 1) { $core_props['tags_names'] = 'Tag names'; $tags_model = $this->getModel('tags'); } } if ($conf['tags_col'] == 2 && !in_array('tags_raw', $conf['columns'])) { echo "<script>alert ('CSV file lacks column \\'tags_raw\\' (Comma separated list of tag ids)');"; echo "window.history.back();"; echo "</script>"; jexit(); } else { if ($conf['tags_col'] == 2) { $core_props['tags_raw'] = 'Tags'; $tags_model = $this->getModel('tags'); } } $conf['core_props'] =& $core_props; // ********************************************************* // Verify that all non core property columns are field names // ********************************************************* $unused_columns = array(); foreach ($conf['columns'] as $colname) { if (!isset($conf['core_props'][$colname]) && !isset($conf['thefields'][$colname])) { $unused_columns[] = $colname; JError::raiseNotice(500, "Column '" . $colname . "' : field name NOT FOUND, column will be ignored<br>"); } } if (count($unused_columns) && !$conf['ignore_unused_cols']) { echo "<script>alert ('File has unused " . count($unused_columns) . " columns \\'" . implode("\\' , \\'", $unused_columns) . "\\'" . "\\n\\n(these field names are not assigned to choosen CONTENT TYPE)," . "\\n\\nplease enable: \"Ignore unused columns\"');"; echo "window.history.back();"; echo "</script>"; jexit(); } // ********************************************************** // Verify that custom specified item ids do not already exist // ********************************************************** if ($conf['id_col']) { // Get 'id' column no $id_col_no = 0; foreach ($conf['columns'] as $col_no => $column) { if ($conf['columns'][$col_no] == 'id') { $id_col_no = $col_no; break; } } // Get custom IDs in csv file $custom_id_arr = array(); foreach ($contents as $fields) { $custom_id_arr[] = $fields[$id_col_no]; } $custom_id_list = "'" . implode("','", $custom_id_arr) . "'"; // Cross check them if they already exist in the DB $q = "SELECT id FROM #__content WHERE id IN (" . $custom_id_list . ")"; $db->setQuery($q); $existing_ids = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray(); if ($existing_ids && count($existing_ids)) { echo "<script>alert ('File has " . count($existing_ids) . " item IDs that already exist: \\'" . implode("\\' , \\'", $existing_ids) . "\\', please fix or set to ignore \\'id\\' column');"; echo "window.history.back();"; echo "</script>"; jexit(); } } // Trim item's data foreach ($contents as $fields) { $fields = flexicontent_html::arrayTrim($fields); } // Set csvfile contens and columns information $conf['contents'] =& $contents; // *************************************************************** // Verify that imported files exist in the media/documents folders // *************************************************************** // Get fields that use files $conf['import_media_folder'] = JRequest::getVar('import_media_folder'); $conf['import_docs_folder'] = JRequest::getVar('import_docs_folder'); $this->checkfiles($conf, $parse_log, $task); $this->parsevalues($conf, $parse_log, $task); if ($task == 'initcsv') { // Set import configuration and file data into session $session->set('csvimport_config', $has_zlib ? base64_encode(zlib_encode(serialize($conf), -15)) : base64_encode(serialize($conf)), 'flexicontent'); $session->set('csvimport_lineno', 0, 'flexicontent'); // Set a total results message and redirect $app->enqueueMessage('Imported task prepared. <br/>' . 'File has ' . count($conf['contents_parsed']) . ' records (content items)' . ' and ' . count($conf['columns']) . ' columns (fields)', 'message'); $this->setRedirect($_SERVER['HTTP_REFERER']); return; } else { // task == 'testcsv' $conf['debug'] = $conf['debug'] ? $conf['debug'] : 2; } } } } // ********************************************************************************* // Handle each row (item) using store() method of the item model to create the items // ********************************************************************************* if ($conf['tags_col']) { $tags_model = $this->getModel('tags'); } $colcount = count($conf['columns']); $itemcount = count($conf['contents_parsed']); $items_per_call = JRequest::getInt('items_per_call', 0); JRequest::setVar('import_media_folder', $conf['import_media_folder']); JRequest::setVar('import_docs_folder', $conf['import_docs_folder']); $lineno = $task == 'testcsv' ? 1 : $lineno + 1; $linelim = $items_per_call ? $lineno + $items_per_call - 1 : $itemcount; $linelim = $linelim > $itemcount ? $itemcount : $linelim; //echo "lineno: $lineno -- linelim: $linelim<br/>"; for (; $lineno <= $linelim; $lineno++) { $_d =& $conf['contents_parsed'][$lineno]; $data = array(); $data['type_id'] = $conf['type_id']; $data['language'] = $conf['language']; $data['catid'] = $conf['maincat']; $data['cid'] = $conf['seccats']; $data['vstate'] = 2; $data['state'] = $conf['state']; // Prepare request variable used by the item's Model if ($task != 'testcsv') { foreach ($_d as $fieldname => $field_values) { if ($fieldname == 'tags_names') { if ($conf['tags_col'] == 1) { // Get tag names from comma separated list, filtering out bad characters $remove = array("\n", "\r\n", "\r"); $tns_list = str_replace($remove, ' ', $field_values); $tns_list = strip_tags($tns_list); $tns_list = preg_replace("/[\"\\\\]/u", "", $tns_list); // "/[\"'\\\]/u" $tns = array_unique(preg_split("/\\s*,\\s*/u", $tns_list)); $tns_quoted = array(); foreach ($tns as $tindex => $tname) { if ($tname) { $tns_quoted[] = $db->Quote($tname); } } if (count($tns_quoted)) { $tns_list_quoted = implode(",", $tns_quoted); $q = "SELECT name FROM #__flexicontent_tags WHERE name IN (" . $tns_list_quoted . ")"; $db->setQuery($q); $tns_e = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray(); $tns_m = array_diff($tns, $tns_e); if (count($tns_m)) { // Create a newline separated list of tag names and then import missing tags, // thus making sure they are inserted into the tags DB table if not already present $tns_list_m = implode("\n", $tns_m); $tags_model->importList($tns_list_m); } // Get tag ids $q = "SELECT id FROM #__flexicontent_tags WHERE name IN (" . $tns_list_quoted . ")"; $db->setQuery($q); $data['tag'] = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray(); } } } else { if ($fieldname == 'tags_raw') { if ($conf['tags_col'] == 2) { // Get tag ids from comma separated list, filtering out bad characters $_tis_list = preg_replace("/[\"'\\\\]/u", "", $field_values); $_tis = array_unique(array_map('intval', $_tis)); $_tis = array_flip($_tis); // Check to use only existing tag ids $_tis_list = implode(",", array_keys($_tis)); $q = "SELECT id FROM #__flexicontent_tags WHERE id IN (" . $_tis_list . ")"; $db->setQuery($q); $data['tag'] = FLEXI_J16GE ? $db->loadColumn() : $db->loadResultArray(); } } else { if (isset($conf['core_props'][$fieldname])) { $data[$fieldname] = $field_values; } else { if (FLEXI_J16GE) { $data['custom'][$fieldname] = $field_values; } } } } } } // Set/Force id to zero to indicate creation of new item, in case item 'id' column is being used $c_item_id = @$data['id']; $data['id'] = 0; $session->set('csvimport_lineno', $lineno, 'flexicontent'); // If testing format then output some information if ($task == 'testcsv') { if ($lineno == 1) { $parse_log .= ' <span class="fc-mssg fc-info"> Testing file format <br/> COLUMNS: ' . implode(', ', $conf['columns']) . '<br/> </span><hr/> '; } foreach ($_d as $i => $flddata) { if (is_string($_d[$i])) { if (mb_strlen($_d[$i], 'UTF-8') > 80) { $_d[$i] = mb_substr(strip_tags($_d[$i]), 0, 80, 'UTF-8') . ' ... '; } } } if ($lineno <= $conf['debug']) { $parse_log .= "<pre><b>Item no {$lineno}:</b>\n" . print_r($_d, true) . "</pre><hr/>"; } else { $parse_log .= "<b>Item no {$lineno}:</b> <br/>" . "<u>TITLE</u>: " . $_d['title'] . "<br/>" . "<u>TEXT</u>: " . $_d['text'] . "<hr/>"; } } else { if (!$model->store($data)) { $conf['failure_count']++; $msg = 'Failed item no: ' . $lineno . ". titled as: '" . $data['title'] . "' : " . $model->getError(); if (FLEXI_J16GE) { JLog::add($msg); } else { $log->addEntry(array('comment' => $msg)); } echo $msg . "<br/>"; } else { $conf['success_count']++; $msg = 'Imported item no: ' . $lineno . ". titled as: '" . $data['title'] . "'"; if (FLEXI_J16GE) { JLog::add($msg); } else { $log->addEntry(array('comment' => $msg)); } echo $msg . "<br/>"; // Try to rename entry if id column is being used if ($conf['id_col'] && $c_item_id) { $item_id = $model->getId(); $q = "UPDATE #__content SET id='" . $c_item_id . "' WHERE id='" . $item_id . "'"; $db->setQuery($q); $db->query(); $q = "UPDATE #__flexicontent_items_ext SET item_id='" . $c_item_id . "' WHERE item_id='" . $item_id . "'"; $db->setQuery($q); $db->query(); $q = "UPDATE #__flexicontent_items_tmp SET id='" . $c_item_id . "' WHERE id='" . $item_id . "'"; $db->setQuery($q); $db->query(); $q = "UPDATE #__flexicontent_tags_item_relations SET itemid='" . $c_item_id . "' WHERE itemid='" . $item_id . "'"; $db->setQuery($q); $db->query(); $q = "UPDATE #__flexicontent_cats_item_relations SET itemid='" . $c_item_id . "' WHERE itemid='" . $item_id . "'"; $db->setQuery($q); $db->query(); $q = "UPDATE #__flexicontent_fields_item_relations SET item_id='" . $c_item_id . "' WHERE item_id='" . $item_id . "'"; $db->setQuery($q); $db->query(); $q = "UPDATE #__flexicontent_items_versions SET item_id='" . $c_item_id . "' WHERE item_id='" . $item_id . "'"; $db->setQuery($q); $db->query(); $q = "UPDATE #__flexicontent_versions SET item_id='" . $c_item_id . "' WHERE item_id='" . $item_id . "'"; $db->setQuery($q); $db->query(); $q = "UPDATE #__flexicontent_favourites SET itemid='" . $c_item_id . "' WHERE itemid='" . $item_id . "'"; $db->setQuery($q); $db->query(); if (FLEXI_J16GE) { $q = "UPDATE #__assets SET id='" . $c_item_id . "' WHERE id='" . $item_id . "'"; } else { $q = "UPDATE #__flexiaccess_acl SET axo='" . $c_item_id . "'" . " WHERE acosection = " . $db->Quote('com_content') . " AND axosection = " . $db->Quote('item') . " AND axo='" . $item_id . "'"; } $db->setQuery($q); $db->query(); } } } } //fclose($fp); // Done nothing more to do if ($task == 'testcsv') { echo $parse_log; echo "\n\n\n" . '<b>please click</b> <a href="JavaScript:window.history.back();">here</a> to return previous page' . "\n\n\n"; jexit(); } if ($lineno == $itemcount) { // Clean item's cache, but is this needed when adding items ? if (FLEXI_J16GE) { $cache = FLEXIUtilities::getCache($group = '', 0); $cache->clean('com_flexicontent_items'); $cache->clean('com_flexicontent_filters'); $cache = FLEXIUtilities::getCache($group = '', 1); $cache->clean('com_flexicontent_items'); $cache->clean('com_flexicontent_filters'); } else { $itemcache = JFactory::getCache('com_flexicontent_items'); $itemcache->clean(); $filtercache = JFactory::getCache('com_flexicontent_filters'); $filtercache->clean(); } // Set a total results message and redirect $msg = 'Imported items: ' . $conf['success_count'] . ' , failed items: ' . $conf['failure_count'] . ', please review (in the logs folder) the import log file: ' . $log_filename; //$app->enqueueMessage($msg, ($conf['failure_count']==0 && $conf['success_count']>0) ? 'message' : 'warning'); //$this->setRedirect($link); // commented out this via AJAX call now } jexit(); }
function log($file, $msg) { jimport('joomla.error.log'); $log =& JLog::getInstance($file); $log->addEntry(array('comment' => 'LOG: ' . $msg)); }
public function post() { //query to get daily, weekly, mohthly & yearly sales $db = JFactory::getDBO(); require_once dirname(__FILE__) . DS . 'helper.php'; $current_date = JRequest::getVar('current_date'); //for log record jimport('joomla.error.log'); $options = array('format' => "{DATE}\t{TIME}\t{USER_ID}\t{COMMENT}\t{CDATE}\t{}"); $log =& JLog::getInstance('com_api.log.php'); $log->setOptions($options); $user =& JFactory::getUser(); $userId = $user->get('id'); $log->addEntry(array('user_id' => $userId, 'comment' => 'This is the comment', 'cdate' => $current_date)); //set offset & date for server $config =& JFactory::getConfig(); $offset = $config->getValue('config.offset'); $offset = ''; $current_date =& JFactory::getDate($current_date, $offset); $current_date = $current_date->toFormat('%F %T'); //daily data $day_start = date_create($current_date)->format('Y-m-d'); $day_start .= ' 00:00:00'; $daily = Sale_Data::total($day_start, $current_date); $daily = Sale_Data::compress($daily); if (!$daily) { $daily = 0; } list($year, $month, $day) = split('[/.-]', $current_date); //weekly data $db = JFactory::getDBO(); $query = "SELECT WEEKDAY('" . $current_date . "')"; $db->setQuery($query); $wstart = $db->loadResult(); $wday = $day - $wstart; $wdate = $year . "-" . $month . "-" . $wday; $weekly = Sale_Data::total($wdate, $current_date); $weekly = Sale_Data::compress($weekly); if (!$weekly) { $weekly = 0; } // monthly data $mdate = $year . "-" . $month . "-01 00:00:00"; $monthly = Sale_Data::total($mdate, $current_date); $monthly = Sale_Data::compress($monthly); if (!$monthly) { $monthly = 0; } //quarterly data $query = "SELECT QUARTER('" . $current_date . "')"; $db->setQuery($query); $res = $db->loadResult(); $query = "SELECT YEAR('" . $current_date . "')"; $db->setQuery($query); $year = $db->loadResult(); switch ($res) { case 1: $qrt = $year . "-01-01"; break; case 2: $qrt = $year . "-04-01"; break; case 3: $qrt = $year . "-07-01"; break; case 4: $qrt = $year . "-10-01"; break; } $quarterly = Sale_Data::total($qrt, $current_date); $quarterly = Sale_Data::compress($quarterly); if (!$quarterly) { $quarterly = 0; } // calender Yearly data $ydate = $year . "-01-01 00:00:00"; $yearly = Sale_Data::total($ydate, $current_date); $yearly = Sale_Data::compress($yearly); if (!$yearly) { $year = 0; } // financial Yearly data $fdate = $year . "-4-1 00:00:00"; $fyearly = Sale_Data::total($fdate, $current_date); $fyearly = Sale_Data::compress($fyearly); if (!$fyearly) { $fyear = 0; } // Currency require JPATH_SITE . DS . "administrator" . DS . "components" . DS . "com_socialads" . DS . "config" . DS . "config.php"; $currency = $socialads_config['currency']; switch ($currency) { case "INR": $currency = "₹"; break; case "USD": $currency = "\$"; break; case "GBP" || "UKP": $currency = "£"; break; case "JPY": $currency = "¥"; break; case "ITL": $currency = "£"; break; case "EUR": $currency = "€"; break; case "CNY": $currency = "¥"; break; case "ZAR": $currency = "R"; break; case "AUD": $currency = "\$"; break; } //send result $result = array(); $result['summary'] = array("daily" => $daily, "weekly" => $weekly, "monthly" => $monthly, "quarterly" => $quarterly, "financial_yearly" => $fyearly, "calender_yearly" => $yearly); $result['attribs'] = array("currency" => $currency); $this->plugin->setResponse($result); }
/** * Upload files * * @since 1.0 */ function upload() { // Check for request forgeries JRequest::checkToken('request') or jexit('Invalid Token'); $user = JFactory::getUser(); $app = JFactory::getApplication(); $task = JRequest::getVar('task'); // calculate access $canupload = $user->authorise('flexicontent.uploadfiles', 'com_flexicontent'); $is_authorised = $canupload; // check access if (!$is_authorised) { if ($task == 'uploads') { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "' . JText::_('FLEXI_ALERTNOTAUTH') . '"}, "id" : "id"}'); } else { JError::raiseNotice(403, JText::_('FLEXI_ALERTNOTAUTH')); $this->setRedirect('index.php?option=com_flexicontent&view=filemanager', ''); } return; } $option = JRequest::getVar('option'); if ($task == 'uploads') { $file = JRequest::getVar('file', '', 'files', 'array'); } else { // Default field <input type="file" is name="Filedata" ... get the file $ffname = JRequest::getCmd('file-ffname', 'Filedata', 'post'); $file = JRequest::getVar($ffname, '', 'files', 'array'); // Refactor the array swapping positions $file = $this->refactorFilesArray($file); // Get nested position, and reach the final file data array $fname_level1 = JRequest::getCmd('fname_level1', null, 'post'); $fname_level2 = JRequest::getCmd('fname_level2', null, 'post'); $fname_level3 = JRequest::getCmd('fname_level3', null, 'post'); if (strlen($fname_level1)) { $file = $file[$fname_level1]; } if (strlen($fname_level2)) { $file = $file[$fname_level2]; } if (strlen($fname_level3)) { $file = $file[$fname_level3]; } } $format = JRequest::getVar('format', 'html', '', 'cmd'); $secure = JRequest::getInt('secure', 1); $secure = $secure ? 1 : 0; $return = JRequest::getVar('return-url', null, '', 'base64'); $filetitle = JRequest::getVar('file-title', ''); $filedesc = JRequest::getVar('file-desc', ''); $filelang = JRequest::getVar('file-lang', ''); $fieldid = JRequest::getVar('fieldid', 0); $u_item_id = JRequest::getVar('u_item_id', 0); $file_mode = JRequest::getVar('folder_mode', 0) ? 'folder_mode' : 'db_mode'; $err = null; $model = $this->getModel('filemanager'); if ($file_mode != 'folder_mode' && $fieldid) { // Check if FORCED secure/media mode parameter exists and if it is forced $field_params = $model->getFieldParams($fieldid); $target_dir = $field_params->get('target_dir', ''); if (strlen($target_dir) && $target_dir != 2) { $secure = $target_dir ? 1 : 0; // force secure / media } else { // allow filter secure via form/URL variable } } // ***************************************** // Check that a file was provided / uploaded // ***************************************** if (!isset($file['name'])) { if ($task == 'uploads') { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "' . JText::_('Filename has invalid characters (or other error occured)') . '"}, "id" : "id"}'); } else { JError::raiseWarning(100, JText::_('Filename has invalid characters (or other error occured)')); $this->setRedirect($_SERVER['HTTP_REFERER'], ''); } return; } // Chunking might be enabled $chunks = JRequest::getInt('chunks'); if ($chunks) { $chunk = JRequest::getInt('chunk'); // Get / Create target directory $targetDir = (ini_get("upload_tmp_dir") ? ini_get("upload_tmp_dir") : sys_get_temp_dir()) . DIRECTORY_SEPARATOR . "fc_fileselement"; if (!file_exists($targetDir)) { @mkdir($targetDir); } // Create name of the unique temporary filename to use for concatenation of the chunks, or get the filename from session $fileName = JRequest::getVar('filename'); $fileName_tmp = $app->getUserState($fileName, date('Y_m_d_') . uniqid()); $app->setUserState($fileName, $fileName_tmp); $filePath_tmp = $targetDir . DIRECTORY_SEPARATOR . $fileName_tmp; // Open temp file if (!($out = @fopen("{$filePath_tmp}", "ab"))) { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream: ' . $fileName_tmp . '."}, "id" : "id"}'); } if (!empty($_FILES)) { if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } if (!($in = @fopen($_FILES["file"]["tmp_name"], "rb"))) { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } } else { if (!($in = @fopen("php://input", "rb"))) { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } } // Read binary input stream and append it to temp file while ($buff = fread($in, 4096)) { fwrite($out, $buff); } @fclose($out); @fclose($in); // If not last chunk terminate further execution if ($chunk < $chunks - 1) { // Return Success JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); } $app->setUserState($fileName, null); // Cleanup left-over files if (file_exists($targetDir)) { foreach (new DirectoryIterator($targetDir) as $fileInfo) { if ($fileInfo->isDot()) { continue; } if (time() - $fileInfo->getCTime() >= 60) { unlink($fileInfo->getRealPath()); } } } //echo "-- chunk: $chunk \n-- chunks: $chunks \n-- targetDir: $targetDir \n--filePath_tmp: $filePath_tmp \n--fileName: $fileName"; //echo "\n"; print_r($_REQUEST); $file['name'] = $fileName; $file['tmp_name'] = $filePath_tmp; $file['size'] = filesize($filePath_tmp); $file['error'] = 0; //echo "\n"; print_r($file); } if ($file_mode == 'folder_mode') { $upload_path_var = 'fc_upload_path_' . $fieldid . '_' . $u_item_id; $path = $app->getUserState($upload_path_var, '') . DS; if ($task != 'uploads') { $app->setUserState($upload_path_var, ''); } // Do not clear in multi-upload } else { $path = $secure ? COM_FLEXICONTENT_FILEPATH . DS : COM_FLEXICONTENT_MEDIAPATH . DS; } jimport('joomla.utilities.date'); // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe jimport('joomla.filesystem.file'); // Sanitize filename further and make unique $params = null; $filename_original = strip_tags($file['name']); // Store original filename before sanitizing the filename $upload_check = flexicontent_upload::check($file, $err, $params); $filename = flexicontent_upload::sanitize($path, $file['name']); $filepath = JPath::clean($path . strtolower($filename)); // Check if uploaded file is valid if (!$upload_check) { if ($format == 'json') { jimport('joomla.error.log'); $log = JLog::getInstance('com_flexicontent.error.php'); $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err)); header('HTTP/1.0 415 Unsupported Media Type'); if ($task == 'uploads') { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Error. Unsupported Media Type!"}, "id" : "id"}'); } else { die('Error. Unsupported Media Type!'); } } else { if ($task == 'uploads') { die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "' . $err . '"}, "id" : "id"}'); } else { JError::raiseNotice(100, JText::_($err)); // REDIRECT if ($return) { $app->redirect(base64_decode($return) . "&" . (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) . "=1"); } } return; } } // Get the extension to record it in the DB $ext = strtolower(flexicontent_upload::getExt($filename)); // Upload Failed //echo "\n". $file['tmp_name'] ." => ". $filepath ."\n"; $move_success = $chunks ? rename($file['tmp_name'], $filepath) : JFile::upload($file['tmp_name'], $filepath); if (!$move_success) { if ($format == 'json') { jimport('joomla.error.log'); $log = JLog::getInstance('com_flexicontent.error.php'); $log->addEntry(array('comment' => 'Cannot upload: ' . $filepath)); header('HTTP/1.0 409 Conflict'); if ($task == 'uploads') { die('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "File already exists"}, "id" : "id"}'); } else { jexit('Error. File already exists'); } } else { if ($task == 'uploads') { die('{"jsonrpc" : "2.0", "error" : {"code": 106, "message": "' . JText::_('FLEXI_UNABLE_TO_UPLOAD_FILE') . '"}, "id" : "id"}'); } else { JError::raiseWarning(100, JText::_('FLEXI_UNABLE_TO_UPLOAD_FILE')); // REDIRECT if ($return) { $app->redirect(base64_decode($return) . "&" . (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) . "=1"); } } return; } // Upload Successful } else { // a. Database mode if ($file_mode == 'db_mode') { if ($format == 'json') { jimport('joomla.error.log'); $log = JLog::getInstance(); $log->addEntry(array('comment' => $filepath)); } $db = JFactory::getDBO(); $user = JFactory::getUser(); $path = $secure ? COM_FLEXICONTENT_FILEPATH . DS : COM_FLEXICONTENT_MEDIAPATH . DS; // JPATH_ROOT . DS . <media_path | file_path> . DS $filepath = $path . $filename; $filesize = file_exists($filepath) ? filesize($filepath) : 0; $obj = new stdClass(); $obj->filename = $filename; $obj->filename_original = $filename_original; $obj->altname = $filetitle ? $filetitle : $filename_original; $obj->url = 0; $obj->secure = $secure; $obj->ext = $ext; $obj->hits = 0; $obj->size = $filesize; $obj->description = $filedesc; $obj->language = $filelang ? $filelang : '*'; $obj->uploaded = JFactory::getDate('now')->toSql(); $obj->uploaded_by = $user->get('id'); // Insert file record in DB $db->insertObject('#__flexicontent_files', $obj); // Get id of new file record $file_id = (int) $db->insertid(); $option = JRequest::getVar('option'); $filter_item = $app->getUserStateFromRequest($option . '.fileselement.item_id', 'item_id', '', 'int'); if ($filter_item) { $session = JFactory::getSession(); $files = $session->get('fileselement.' . $filter_item, null); if (!$files) { $files = array(); } $files[] = $db->insertid(); $session->set('fileselement.' . $filter_item, $files); } // b. Custom Folder mode } else { $file_id = 0; } // JSON output: Terminate printing a message if ($format == 'json') { if ($task == 'uploads') { // Return Success JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); } else { jexit('Upload complete'); } // Normal output: Redirect setting a message } else { if ($task == 'uploads') { die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); } else { $app->enqueueMessage(JText::_('FLEXI_UPLOAD_COMPLETE')); if (!$return) { return $file_id; } // No return URL, return the file ID $this->setRedirect(base64_decode($return) . "&newfileid=" . $file_id . "&newfilename=" . base64_encode($filename) . "&" . (FLEXI_J30GE ? JSession::getFormToken() : JUtility::getToken()) . "=1", ''); } } } }
function uploadOriginalFile($field, &$post, $file) { $app = JFactory::getApplication(); $format = JRequest::getVar('format', 'html', '', 'cmd'); $err = null; // Get the component configuration $cparams = JComponentHelper::getParams('com_flexicontent'); $params = clone $cparams; // Merge field parameters into the global parameters $fparams = $field->parameters; $params->merge($fparams); jimport('joomla.utilities.date'); jimport('joomla.filesystem.file'); jimport('joomla.client.helper'); // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe $file['name'] = JFile::makeSafe($file['name']); $all_media = $field->parameters->get('list_all_media_files', 0); $unique_thumb_method = $field->parameters->get('unique_thumb_method', 0); $image_source = $field->parameters->get('image_source', 0); // This should be always ZERO inside this function if ($image_source > 1) { global $fc_folder_mode_err; if (empty($fc_folder_mode_err[$field->id])) { echo __FUNCTION__ . "(): folder-mode: " . $image_source . " not implemented please change image-source mode in image/gallery field with id: " . $field->id; $fc_folder_mode_err[$field->id] = 1; $image_source = 1; } } // FLAG to indicate if images are shared across fields, has the effect of adding field id to image thumbnails $multiple_image_usages = !$image_source && $all_media && $unique_thumb_method == 0; $extra_prefix = $multiple_image_usages ? 'fld' . $field->id . '_' : ''; if (isset($file['name']) && $file['name'] != '') { // only handle the secure folder $path = COM_FLEXICONTENT_FILEPATH . DS; //sanitize filename further and make unique $filename = flexicontent_upload::sanitize($path, $file['name']); $filepath = JPath::clean(COM_FLEXICONTENT_FILEPATH . DS . strtolower($filename)); //perform security check according if (!flexicontent_upload::check($file, $err, $params)) { if ($format == 'json') { jimport('joomla.error.log'); $log = JLog::getInstance('com_flexicontent.error.php'); $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err)); header('HTTP/1.0 415 Unsupported Media Type'); die('Error. Unsupported Media Type!'); } else { JError::raiseNotice(100, $field->label . ' : ' . JText::_($err)); return false; } } //get the extension to record it in the DB $ext = strtolower(JFile::getExt($filename)); if (!JFile::upload($file['tmp_name'], $filepath)) { if ($format == 'json') { jimport('joomla.error.log'); $log = JLog::getInstance('com_flexicontent.error.php'); $log->addEntry(array('comment' => 'Cannot upload: ' . $filepath)); header('HTTP/1.0 409 Conflict'); jexit('Error. File already exists'); } else { JError::raiseWarning(100, $field->label . ' : ' . JText::_('Error. Unable to upload file')); return false; } } else { $db = JFactory::getDBO(); $user = JFactory::getUser(); $config = JFactory::getConfig(); $timezone = $config->get('offset'); $date = JFactory::getDate('now'); $date->setTimeZone(new DateTimeZone($timezone)); $obj = new stdClass(); $obj->filename = $filename; $obj->altname = $file['name']; $obj->url = 0; $obj->secure = 1; $obj->ext = $ext; $obj->hits = 0; $obj->uploaded = FLEXI_J16GE ? $date->toSql() : $date->toMySQL(); $obj->uploaded_by = $user->get('id'); if ($format == 'json') { jimport('joomla.error.log'); $log = JLog::getInstance(); $log->addEntry(array('comment' => $filepath)); $db->insertObject('#__flexicontent_files', $obj); jexit('Upload complete'); } else { $db->insertObject('#__flexicontent_files', $obj); $app->enqueueMessage($field->label . ' : ' . JText::_('Upload complete')); $sizes = array('l', 'm', 's', 'b'); foreach ($sizes as $size) { // create the thumbnail $this->create_thumb($field, $filename, $size, $origpath = '', $destpath = '', $copy_original = 0, $extra_prefix); // set the filename for posting $post['originalname'] = $filename; } return true; } } } else { $err = 'File upload failed'; JError::raiseNotice(100, $field->label . ' : ' . JText::_($err)); return false; } }
/** * Upload a file * * @since 1.5 */ function upload() { $params = JComponentHelper::getParams('com_media'); // Check for request forgeries if (!JSession::checkToken('request')) { $response = array('status' => '0', 'error' => JText::_('JINVALID_TOKEN')); echo json_encode($response); return; } // Get the user $user = JFactory::getUser(); $log = JLog::getInstance('upload.error.php'); // Get some data from the request $file = JRequest::getVar('Filedata', '', 'files', 'array'); $folder = JRequest::getVar('folder', '', '', 'path'); $return = JRequest::getVar('return-url', null, 'post', 'base64'); if ($_SERVER['CONTENT_LENGTH'] > $params->get('upload_maxsize', 0) * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('upload_max_filesize') * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('post_max_size') * 1024 * 1024 || $_SERVER['CONTENT_LENGTH'] > (int) ini_get('memory_limit') * 1024 * 1024) { $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_WARNFILETOOLARGE')); echo json_encode($response); return; } // Set FTP credentials, if given JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe $file['name'] = JFile::makeSafe($file['name']); if (isset($file['name'])) { // The request is valid $err = null; $filepath = JPath::clean(COM_MEDIA_BASE . '/' . $folder . '/' . strtolower($file['name'])); if (!MediaHelper::canUpload($file, $err)) { $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err)); $response = array('status' => '0', 'error' => JText::_($err)); echo json_encode($response); return; } // Trigger the onContentBeforeSave event. JPluginHelper::importPlugin('content'); $dispatcher = JDispatcher::getInstance(); $object_file = new JObject($file); $object_file->filepath = $filepath; $result = $dispatcher->trigger('onContentBeforeSave', array('com_media.file', &$object_file)); if (in_array(false, $result, true)) { // There are some errors in the plugins $log->addEntry(array('comment' => 'Errors before save: ' . $filepath . ' : ' . implode(', ', $object_file->getErrors()))); $response = array('status' => '0', 'error' => JText::plural('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); echo json_encode($response); return; } if (JFile::exists($filepath)) { // File exists $log->addEntry(array('comment' => 'File exists: ' . $filepath . ' by user_id ' . $user->id)); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_FILE_EXISTS')); echo json_encode($response); return; } elseif (!$user->authorise('core.create', 'com_media')) { // File does not exist and user is not authorised to create $log->addEntry(array('comment' => 'Create not permitted: ' . $filepath . ' by user_id ' . $user->id)); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_CREATE_NOT_PERMITTED')); echo json_encode($response); return; } $file = (array) $object_file; if (!JFile::upload($file['tmp_name'], $file['filepath'])) { // Error in upload $log->addEntry(array('comment' => 'Error on upload: ' . $filepath)); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE')); echo json_encode($response); return; } else { // Trigger the onContentAfterSave event. $dispatcher->trigger('onContentAfterSave', array('com_media.file', &$object_file, true)); $log->addEntry(array('comment' => $folder)); $response = array('status' => '1', 'error' => JText::sprintf('COM_MEDIA_UPLOAD_COMPLETE', substr($file['filepath'], strlen(COM_MEDIA_BASE)))); echo json_encode($response); return; } } else { $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_BAD_REQUEST')); echo json_encode($response); return; } }
/** * Upload a file * * @param array $params - the parameters of uploaded file * * @return array * @since 1.0 */ function upload($params = array()) { // Check for request forgeries if (!JRequest::checkToken('request')) { $response = array('status' => '0', 'error' => JText::_('JINVALID_TOKEN')); return $response; } // Get the user $user = JFactory::getUser(); $log = JLog::getInstance('upload.error.php'); // Get some data from the reques $filedataName = !empty($params['filedataName']) ? $params['filedataName'] : 'Filedata'; $file = JRequest::getVar($filedataName, '', 'files', 'array'); $folder = '/data'; //JRequest::getVar('folder', '/data', '', 'path'); $return = JRequest::getVar('return-url', null, 'post', 'base64'); // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); // Make the filename safe $file['name'] = JFile::makeSafe($file['name']); if (isset($file['name'])) { // The request is valid $err = null; $filepath = JPath::clean(JPATH_COMPONENT . DS . $folder . DS . strtolower($file['name'])); if (!MediaHelper::canUpload($file, $err)) { $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err)); $response = array('status' => '0', 'error' => JText::_($err)); return $response; } // Trigger the onContentBeforeSave event. JPluginHelper::importPlugin('content'); $dispatcher = JDispatcher::getInstance(); $object_file = new JObject($file); $object_file->filepath = $filepath; $result = $dispatcher->trigger('onContentBeforeSave', array('com_media.file', $object_file)); if (in_array(false, $result, true)) { // There are some errors in the plugins $log->addEntry(array('comment' => 'Errors before save: ' . $filepath . ' : ' . implode(', ', $object_file->getErrors()))); $response = array('status' => '0', 'error' => JText::plural('COM_MEDIA_ERROR_BEFORE_SAVE', count($errors = $object_file->getErrors()), implode('<br />', $errors))); return $response; } if (JFile::exists($filepath) && empty($params['overwrite'])) { // File exists $log->addEntry(array('comment' => 'File exists: ' . $filepath . ' by user_id ' . $user->id)); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_FILE_EXISTS')); return $response; } elseif (!$user->authorise('core.create', 'com_media')) { // File does not exist and user is not authorised to create $log->addEntry(array('comment' => 'Create not permitted: ' . $filepath . ' by user_id ' . $user->id)); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_CREATE_NOT_PERMITTED')); return $response; } $file = (array) $object_file; if (!JFile::upload($file['tmp_name'], $file['filepath'])) { // Error in upload $log->addEntry(array('comment' => 'Error on upload: ' . $filepath)); $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE')); return $response; } else { // Trigger the onContentAfterSave event. //$dispatcher->trigger('onContentAfterSave', array('com_media.file', &$object_file), null); $log->addEntry(array('comment' => $folder)); $response = array('status' => '1', 'error' => JText::sprintf('COM_MEDIA_UPLOAD_COMPLETE', substr($file['filepath'], strlen('COM_MEDIA_BASE'))), 'file' => $file); return $response; } } else { $response = array('status' => '0', 'error' => JText::_('COM_MEDIA_ERROR_BAD_REQUEST')); return $response; } }