Removal of alpahnumeric characters, SQL-safe slash-added strings, HTML-friendly strings, and all of the above on arrays.
Пример #1
0
 function purchase_product()
 {
     // Clean up the post
     uses('sanitize');
     $clean = new Sanitize();
     $clean->paranoid($_POST);
     // Check if we have an active cart, if there is no order_id set, then lets create one.
     if (!isset($_SESSION['Customer']['order_id'])) {
         $new_order = array();
         $new_order['Order']['order_status_id'] = 0;
         // Get default shipping & payment methods and assign them to the order
         $default_payment = $this->Order->PaymentMethod->find(array('default' => '1'));
         $new_order['Order']['payment_method_id'] = $default_payment['PaymentMethod']['id'];
         $default_shipping = $this->Order->ShippingMethod->find(array('default' => '1'));
         $new_order['Order']['shipping_method_id'] = $default_shipping['ShippingMethod']['id'];
         // Save the order
         $this->Order->save($new_order);
         $order_id = $this->Order->getLastInsertId();
         $_SESSION['Customer']['order_id'] = $order_id;
         global $order;
         $order = $new_order;
     }
     // Add the product to the order from the component
     $this->OrderBase->add_product($_POST['product_id'], $_POST['product_quantity']);
     global $config;
     $content = $this->Content->read(null, $_POST['product_id']);
     $this->redirect('/product/' . $content['Content']['alias'] . $config['URL_EXTENSION']);
 }
Пример #2
0
 function getrss()
 {
     uses('Sanitize');
     Configure::write('debug', '0');
     //turn debugging off; debugging breaks ajax
     $this->layout = 'ajax';
     $mrClean = new Sanitize();
     $limit = 5;
     $start = 0;
     if (empty($this->params['form']['url'])) {
         die('Incorrect use');
     }
     $url = $this->params['form']['url'];
     if (!empty($this->params['form']['limit'])) {
         $limit = $mrClean->paranoid($this->params['form']['limit']);
     }
     if (!empty($this->params['form']['start'])) {
         $start = $mrClean->paranoid($this->params['form']['start']);
     }
     $feed = $this->Simplepie->feed_paginate($url, (int) $start, (int) $limit);
     $out['totalCount'] = $feed['quantity'];
     $out['title'] = $feed['title'];
     $out['image_url'] = $feed['image_url'];
     $out['image_width'] = $feed['image_width'];
     $out['image_height'] = $feed['image_height'];
     foreach ($feed['items'] as $item) {
         $tmp['title'] = strip_tags($item->get_title());
         $tmp['url'] = strip_tags($item->get_permalink());
         $tmp['description'] = strip_tags($item->get_description(), '<p><br><img><a><b>');
         $tmp['date'] = strip_tags($item->get_date('d/m/Y'));
         $out['items'][] = $tmp;
     }
     $this->set('json', $out);
 }
Пример #3
0
 /**
  * clean keywords string
  */
 private function _cleanKeywords($data)
 {
     $keywords = $data['keywords'];
     if (!empty($keywords)) {
         $san = new Sanitize();
         $keywords = $san->html($keywords);
     } else {
         $keywords = '';
     }
     return $keywords;
 }
Пример #4
0
 public function detalleIndex_get()
 {
     $sanador = new Sanitize();
     $user = $sanador->clean_string($this->get('usuario'));
     $validacion = $this->validaUsuario($user);
     if ($validacion) {
         $respuesta = $this->llenaIndex($user);
     } else {
         $respuesta = new Response(400, "withOutUser");
     }
     $this->response($respuesta);
 }
Пример #5
0
 public function logueo_get()
 {
     $sanador = new Sanitize();
     $user = $sanador->clean_string($this->get('usuario'));
     $pass = $sanador->clean_string($this->get('pass'));
     $response = $this->m_consultas->login($user, $pass);
     if ($response == FALSE) {
         $respuesta = new Response(400, "userPassFail");
         $this->response($respuesta);
     }
     $respuesta = new Response(200, $response);
     $this->response($respuesta);
 }
Пример #6
0
 function addComment(&$Model, $params, $user_id, $tpl_params = array(), $comment_type_name = null, $model_alias = null)
 {
     $mrClean = new Sanitize();
     $notification_data = a();
     $foreign_id = $params['form']['foreign_id'];
     $text = $mrClean->html($params['form']['comment']);
     $comment = array('Comment' => array('body' => $text, 'name' => $user_id, 'email' => '*****@*****.**'));
     $out = $Model->createComment($foreign_id, $comment);
     $comment_id = $Model->Comment->id;
     if (!$model_alias) {
         $model_alias = $Model->alias;
     }
     // Retrieve ids belonging to users that have be notified (eg each users that commented this object before)
     $comments = Set::extract($this->getComments($Model, $foreign_id, TRUE), '{n}.Comment.name');
     // Remove duplicated values
     $tbn = array_unique($comments);
     // Retrieve owner of the commented object
     $owner = $Model->read('user_id', $foreign_id);
     $owner_id = $owner[$model_alias]['user_id'];
     // owner should be notified as well
     if (!in_array($owner_id, $tbn)) {
         array_push($tbn, $owner_id);
     }
     $users = array_diff($tbn, array($user_id));
     if (!empty($users)) {
         $this->setupUserModel();
         $commenter = $this->user->read(array('name', 'surname'), $user_id);
         $owner = $this->user->read(array('name', 'surname'), $owner_id);
         $subject = $this->Conf->get('Site.name') . " comment notification";
         $domain = $this->Conf->get('Organization.domain');
         foreach ($users as $c_id) {
             // check whether the user is can be notified or not
             $active = $this->Acl->check(array('model' => 'User', 'foreign_key' => $c_id), 'site');
             $nfb = $this->user->read('notification', $c_id);
             if ($active && $nfb['User']['notification']) {
                 if ($c_id == $owner_id) {
                     $is_owner = true;
                 } else {
                     $is_owner = false;
                 }
                 array_push($notification_data, array('from' => 'noreply@' . $domain, 'to' => $this->user->getemail($c_id, $this->Conf->get('Organization.domain')), 'subject' => $subject, 'own' => $is_owner, 'owner' => $owner['User'], 'commenter' => $commenter['User']));
             }
         }
     }
     $Model->addtotimeline($tpl_params, null, 'comment', $user_id, $model_alias, $foreign_id, $comment_id, $comment_type_name);
     # clear cache
     clearCache($this->cacheName, '', '');
     return $notification_data;
 }
Пример #7
0
 function createComment(&$model, $id, $data = array())
 {
     if (!empty($data[$this->__settings[$model->alias]['class']])) {
         unset($data[$model->alias]);
         $model->Comment->validate = array($this->__settings[$model->alias]['column_author'] => array('notempty' => array('rule' => array('notempty'))), $this->__settings[$model->alias]['column_content'] => array('notempty' => array('rule' => array('notempty'))), $this->__settings[$model->alias]['column_email'] => array('notempty' => array('rule' => array('notempty')), 'email' => array('rule' => array('email'), 'message' => 'Please enter a valid email address')), $this->__settings[$model->alias]['column_class'] => array('notempty' => array('rule' => array('notempty'))), $this->__settings[$model->alias]['column_foreign_id'] => array('notempty' => array('rule' => array('notempty'))), $this->__settings[$model->alias]['column_status'] => array('notempty' => array('rule' => array('notempty'))), $this->__settings[$model->alias]['column_points'] => array('notempty' => array('rule' => array('notempty')), 'numeric' => array('rule' => array('numeric'))));
         $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_class']] = $model->alias;
         $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_foreign_id']] = $id;
         $data[$this->__settings[$model->alias]['class']] = $this->_rateComment($model, $data['Comment']);
         if ($data[$this->__settings[$model->alias]['class']]['status'] == 'spam') {
             $data[$this->__settings[$model->alias]['class']]['active'] == 0;
         } else {
             if (Configure::read('Comments.auto_moderate') === true && $data[$this->__settings[$model->alias]['class']]['status'] != 'spam') {
                 $data[$this->__settings[$model->alias]['class']]['active'] == 1;
             }
         }
         if ($this->__settings[$model->alias]['sanitize']) {
             App::import('Sanitize');
             $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_author']] = Sanitize::clean($data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_author']]);
             $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_email']] = Sanitize::clean($data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_email']]);
             $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_content']] = Sanitize::clean($data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_content']]);
         } else {
             $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_author']] = $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_author']];
             $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_email']] = $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_email']];
             $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_content']] = $data[$this->__settings[$model->alias]['class']][$this->__settings[$model->alias]['column_content']];
         }
         if ($this->_checkForEmptyVal($data[$this->__settings[$model->alias]['class']]) == false) {
             $model->Comment->create();
             if ($model->Comment->save($data)) {
                 return true;
             }
         }
     }
     return false;
 }
Пример #8
0
 function getListingFavorites($listing_id, $user_id, $passedArgs)
 {
     $conditions = array();
     $avatar = Sanitize::getInt($passedArgs['module'], 'avatar', 1);
     // Only show users with avatars
     $count = Sanitize::getInt($passedArgs['module'], 'module_limit', 5);
     $module_id = Sanitize::getInt($passedArgs, 'module_id');
     $rand = Sanitize::getFloat($passedArgs, 'rand');
     $fields = array('Community.' . $this->realKey . ' AS `User.user_id`', 'User.name AS `User.name`', 'User.username AS `User.username`');
     if ($avatar) {
         $conditions[] = 'Community.thumb <> "components/com_community/assets/default_thumb.jpg"';
     }
     if ($listing_id) {
         $conditions[] = 'Community.' . $this->realKey . ' in (SELECT user_id FROM #__jreviews_favorites WHERE content_id = ' . $listing_id . ')';
     }
     $order = array('RAND(' . $rand . ')');
     $joins = array('LEFT JOIN #__users AS User ON Community.' . $this->realKey . ' = User.id');
     $profiles = $this->findAll(array('fields' => $fields, 'conditions' => $conditions, 'order' => $order, 'joins' => $joins));
     if (Sanitize::getInt($passedArgs['module'], 'ajax_nav', 1)) {
         $fields = array('count(Community.' . $this->realKey . ')');
         $group = array('Community.' . $this->realKey);
         $this->count = $this->findCount(array('fields' => $fields, 'conditions' => $conditions, 'group' => $group, 'joins' => $joins));
     } else {
         $this->count = Sanitize::getInt($passedArgs['module'], 'module_limit', 5);
     }
     return $this->addProfileInfo($profiles, 'User', 'user_id');
 }
Пример #9
0
 public function verifyUserByToken($username, $token)
 {
     $username = Sanitize::html($username);
     $token = Sanitize::html($token);
     $username = trim($username);
     $token = trim($token);
     if (empty($username) || empty($token)) {
         Log::set(__METHOD__ . LOG_SEP . 'Username or Token-email empty. Username: '******' - Token-email: ' . $token);
         return false;
     }
     $user = $this->dbUsers->getDb($username);
     if ($user == false) {
         Log::set(__METHOD__ . LOG_SEP . 'Username does not exist: ' . $username);
         return false;
     }
     $currentTime = Date::current(DB_DATE_FORMAT);
     if ($user['tokenEmailTTL'] < $currentTime) {
         Log::set(__METHOD__ . LOG_SEP . 'Token-email expired: ' . $username);
         return false;
     }
     if ($token === $user['tokenEmail']) {
         // Set the user loggued.
         $this->setLogin($username, $user['role']);
         // Invalidate the current token.
         $this->dbUsers->generateTokenEmail($username);
         Log::set(__METHOD__ . LOG_SEP . 'User logged succeeded by Token-email - Username: '******'Token-email incorrect.');
     }
     return false;
 }
Пример #10
0
    public function adminBodyEnd()
    {
        global $layout;
        $html = '';
        // Load CSS and JS only on Controllers in array.
        if (in_array($layout['controller'], $this->loadWhenController)) {
            $pluginPath = $this->htmlPath();
            $html = '<script>' . PHP_EOL;
            $html .= '$(document).ready(function() { ' . PHP_EOL;
            $html .= 'var simplemde = new SimpleMDE({
					element: document.getElementById("jscontent"),
					status: false,
					toolbarTips: true,
					toolbarGuideIcon: true,
					autofocus: false,
					lineWrapping: true,
					autoDownloadFontAwesome: false,
					indentWithTabs: true,
					tabSize: ' . $this->getDbField('tabSize') . ',
					spellChecker: false,
					toolbar: [' . Sanitize::htmlDecode($this->getDbField('toolbar')) . ']
			});';
            $html .= '$("#jsaddImage").on("click", function() {
					var filename = $("#jsimageList option:selected" ).text();
					if(!filename.trim()) {
						return false;
					}
					var text = simplemde.value();
					simplemde.value(text + "![alt text]("+filename+")" + "\\n");
			});';
            $html .= '}); </script>';
        }
        return $html;
    }
Пример #11
0
 public function s()
 {
     $result = array();
     if (isset($this->request->query['term'])) {
         $keyword = Sanitize::clean($this->request->query['term']);
     }
     if (!empty($keyword)) {
         $cacheKey = "ElectionsS{$keyword}";
         $result = Cache::read($cacheKey, 'long');
         if (!$result) {
             $keywords = explode(' ', $keyword);
             $countKeywords = 0;
             $conditions = array('Election.parent_id IS NOT NULL');
             foreach ($keywords as $k => $keyword) {
                 $keyword = trim($keyword);
                 if (!empty($keyword) && ++$countKeywords < 4) {
                     $conditions[] = "Election.keywords LIKE '%{$keyword}%'";
                 }
             }
             $result = $this->Election->find('all', array('fields' => array('Election.id', 'Election.name', 'Election.lft', 'Election.rght'), 'conditions' => $conditions, 'limit' => 50));
             foreach ($result as $k => $v) {
                 $parents = $this->Election->getPath($v['Election']['id'], array('name'));
                 $result[$k]['Election']['name'] = implode(' > ', Set::extract($parents, '{n}.Election.name'));
             }
             Cache::write($cacheKey, $result, 'long');
         }
     }
     $this->set('result', $result);
 }
 function index($params)
 {
     $this->action = 'directory';
     // Set view file
     # Read module params
     $dir_id = cleanIntegerCommaList(Sanitize::getString($this->params['module'], 'dir_ids'));
     $conditions = array();
     $order = array();
     $cat_id = '';
     $section_id = '';
     $directories = $this->Directory->getTree($dir_id, true);
     if ($menu_id = Sanitize::getInt($this->params, 'Itemid')) {
         $menuParams = $this->Menu->getMenuParams($menu_id);
     }
     # Category auto detect
     $ids = CommonController::_discoverIDs($this);
     extract($ids);
     if ($cat_id != '' && $section_id == '') {
         $cat_id = cleanIntegerCommaList($cat_id);
         $sql = "SELECT section FROM #__categories WHERE id IN (" . $cat_id . ")";
         $this->_db->setQuery($sql);
         $section_id = $this->_db->loadResult();
     }
     $this->set(array('directories' => $directories, 'cat_id' => is_numeric($cat_id) && $cat_id > 0 ? $cat_id : false, 'section_id' => $section_id));
     return $this->render('modules', 'directories');
 }
 function index($params)
 {
     $this->action = 'directory';
     // Trigger assets helper method
     if ($this->_user->id === 0) {
         $this->cacheAction = Configure::read('Cache.expires');
     }
     $page = array('title' => '', 'show_title' => 0);
     $conditions = array();
     $order = array();
     if ($menu_id = Sanitize::getInt($this->params, 'Itemid')) {
         $menuParams = $this->Menu->getMenuParams($menu_id);
         $page['title'] = Sanitize::getString($menuParams, 'title');
         $page['show_title'] = Sanitize::getString($menuParams, 'dirtitle', 0);
     }
     $override_keys = array('dir_show_alphaindex', 'dir_cat_images', 'dir_columns', 'dir_cat_num_entries', 'dir_category_hide_empty', 'dir_category_levels', 'dir_cat_format');
     if (Sanitize::getBool($menuParams, 'dir_overrides')) {
         $overrides = array_intersect_key($menuParams, array_flip($override_keys));
         $this->Config->override($overrides);
     }
     if ($this->cmsVersion == CMS_JOOMLA15) {
         $directories = $this->Directory->getTree(Sanitize::getString($this->params, 'dir'));
     } else {
         $directories = $this->Category->findTree(array('level' => $this->Config->dir_cat_format === 0 ? 2 : $this->Config->dir_category_levels, 'menu_id' => true, 'dir_id' => Sanitize::getString($this->params, 'dir'), 'pad_char' => ''));
     }
     $this->set(array('page' => $page, 'directories' => $directories));
     return $this->render('directories', 'directory');
 }
 function index()
 {
     $this->layout = '';
     $login = true;
     //	Verifica se há dados em POST
     if ($this->data) {
         //		Disponibiliza os dados postados para a model
         $this->Funcionario->set($this->data);
         //		Verifica as regras de validação
         //if($this->Funcionario->validates()){
         //		Consulta a função criada na model para validar o login, o método Sanitize::clean torna a string livre de sql hacks
         $result = $this->Funcionario->checkUsuario(Sanitize::clean($this->data));
         if ($result) {
             $this->Session->start();
             $_SESSION['funcionario'] = array('id' => $result['Funcionario']['id'], 'data' => date('d-m-Y'), 'hora' => date('h:m:i'), 'perfil_id' => $result['Funcionario']['perfil_id']);
             if ($result['Funcionario']['perfil_id'] == 1) {
                 $this->redirect('/dashboard');
             } else {
                 //						$this->redirect('/dashboard/index') ;
             }
         } else {
             $this->set('error', true);
         }
         //}
     }
 }
Пример #15
0
 /**
  * Build new instance
  * @param type $config 
  * @return
  */
 public static function setInstance($config = null)
 {
     if (is_null($config)) {
         $config = HTMLPurifier_Config::createDefault();
     }
     self::$_instance = new HTMLPurifier($config);
 }
Пример #16
0
 function paranoid($vars)
 {
     foreach ($vars as &$var) {
         $var = Sanitize::paranoid($var, array('.', '-', '='));
     }
     return $vars;
 }
Пример #17
0
 /**
  * This callback method extract exif data from image and sets fields as customized in settings.
  *
  * @param  Model   $model Object of model
  *
  * @return boolean Return method's status
  */
 function beforeValidate(&$model)
 {
     // If photo is uploaded
     if (isset($model->data[$model->name][$this->settings[$model->name]['filename']]) && 0 == $model->data[$model->name][$this->settings[$model->name]['filename']]['error']) {
         // Name of image file
         //$filename = $model->data[$model->name][$this->settings[$model->name]['filename']]['tmp_name'];
         $filename = WWW_ROOT . 'files' . DS . 'pictures' . DS . $model->data[$model->name][$this->settings[$model->name]['filename']];
         // Read exif data from file
         $exif = read_exif_data_raw($filename, 0);
         // If exif data contains maker note then set it empty
         if (isset($exif['SubIFD']['MakerNote'])) {
             $exif['SubIFD']['MakerNote'] = '';
         }
         // Create new sanitize object and clean exif data
         Sanitize::clean($exif);
         if (isset($exif['SubIFD']['DateTimeOriginal']) && isset($this->settings[$model->name]['exifDateField'])) {
             $model->data[$model->name][$this->settings[$model->name]['exifDateField']] = date($this->settings[$model->name]['exifDateFormat'], strtotime($exif['SubIFD']['DateTimeOriginal']));
         }
         // If the GPS Latitude and Longitude is set then add to proper fields
         if (isset($exif['GPS'])) {
             if (isset($this->settings[$model->name]['gpsLattitudeField'])) {
                 $model->data[$model->name][$this->settings[$model->name]['gpsLattitudeField']] = $exif['GPS']['Latitude'];
             }
             if (isset($this->settings[$model->name]['gpsLattitudeField'])) {
                 $model->data[$model->name][$this->settings[$model->name]['gpsLongitudeField']] = $exif['GPS']['Longitude'];
             }
         }
         // Store serialized exif data in model's data
         if (isset($this->settings[$model->name]['exifField'])) {
             $model->data[$model->name][$this->settings[$model->name]['exifField']] = serialize($exif);
         }
     }
     return true;
 }
Пример #18
0
 /**
  * get_slides
  *
  */
 public function get_slides()
 {
     $this->Prg->commonProcess();
     $add_query = array('Slide.convert_status = ' . SUCCESS_CONVERT_COMPLETED);
     $val = isset($this->passedArgs['created_f']) ? $this->passedArgs['created_f'] : null;
     if (!empty($val)) {
         $add_query[] = "Slide.created >= '" . Sanitize::clean($val) . "'";
     }
     $val = isset($this->passedArgs['created_t']) ? $this->passedArgs['created_t'] : null;
     if (!empty($val)) {
         $add_query[] = "Slide.created <= '" . Sanitize::clean($val) . "'";
     }
     $this->Paginator->settings = array('conditions' => array($this->Slide->parseCriteria($this->passedArgs), $add_query), 'limit' => 200, 'recursive' => 1, 'order' => array('created' => 'desc'));
     try {
         $records = $this->Paginator->paginate('Slide');
     } catch (Exception $e) {
         $this->response->statusCode(400);
         $result['error']['message'] = __('Failed to retrieve results');
         $this->set('error', $result['error']);
         return $this->render('slides');
     }
     $this->response->statusCode(200);
     $this->set('slides', $records);
     return $this->render('slides');
 }
Пример #19
0
 function google($address)
 {
     $this->_API['google'] = str_replace('{google_url}', Sanitize::getString($this->Config, 'geomaps.google_url', 'http://maps.google.com'), $this->_API['google']);
     $geoData = false;
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_URL, sprintf($this->_API['google'], urlencode($address)));
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     $response = trim(curl_exec($curl));
     // Process JSON
     if (!empty($response)) {
         $data = json_decode($response);
         if ($data->status == "OK" && is_array($data->results) && ($result = $data->results[0])) {
             $status = 200;
             $elev = 0;
             $lat = $result->geometry->location->lat;
             $lon = $result->geometry->location->lng;
             if (!is_numeric($lat) || !is_numeric($lon)) {
                 $status = 'error';
             }
             $geoData = array('status' => $status, 'lon' => $lon, 'lat' => $lat, 'elev' => $elev);
         }
     }
     curl_close($curl);
     return $geoData;
 }
Пример #20
0
 function google($address)
 {
     $this->_API['google'] = str_replace('{google_url}', Sanitize::getString($this->Config, 'geomaps.google_url', 'http://maps.google.com'), $this->_API['google']);
     $geoData = false;
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_URL, sprintf($this->_API['google'], urlencode($address)));
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     $response = trim(curl_exec($curl));
     // Process CSV
     if ($response != '' && $response != 620 && count(explode(',', $response)) > 3) {
         // Split pieces of data by the comma that separates them
         list($status, $elev, $lat, $lon) = explode(",", $response);
         if (!is_numeric($lat) || !is_numeric($lon)) {
             $status = 'error';
         }
         $geoData = array('status' => $status, 'lon' => $lon, 'lat' => $lat, 'elev' => $elev);
         // More complete data can be found via XML
         // Create SimpleXML object from XML Content
         //                    $xmlObject = simplexml_load_string($xmlContent);
         //                    $localObject = $xmlObject->Response;
         //                    prx($localObject);
     }
     curl_close($curl);
     return $geoData;
 }
 /**
  * Authenticates the identity contained in a request.  Will use the `settings.userModel`, and `settings.fields`
  * to find POST data that is used to find a matching record in the `settings.userModel`.  Will return false if
  * there is no post data, either username or password is missing, of if the scope conditions have not been met.
  * @author DaiNT
  * @date: 2013/05/23
  * @param CakeRequest $request The request that contains login information.
  * @param CakeResponse $response Unused response object.
  * @return mixed.  False on login failure.  An array of User data on success.
  */
 public function authenticate(CakeRequest $request, CakeResponse $response)
 {
     if (isset($request->data['type'])) {
         $type = $request->data['type'];
         if (!isset($this->settings['types'][$type])) {
             throw new Exception(__('Type %s login not setting', $type));
         }
         $types = $this->settings['types'];
         $this->settings = array_merge(array('types' => $types), $types[$type]);
     }
     // if not set model in from then reset to request
     if (AppUtility::checkIsMobile()) {
         $this->settings['fields']['password'] = '******';
     }
     $fields = $this->settings['fields'];
     $model = $this->settings['userModel'];
     $userName = Sanitize::paranoid($request->data[$model][$fields['username']]);
     $password = Sanitize::paranoid($request->data[$model][$fields['password']]);
     if (empty($request->data[$model])) {
         $request->data[$model] = array($fields['username'] => isset($userName) ? $userName : null, $fields['password'] => isset($password) ? $password : null);
     }
     $user = parent::authenticate($request, $response);
     if (!empty($user) && is_array($user) && isset($request->data[$model]['system_permission'])) {
         $user['system_permission'] = $request->data[$model]['system_permission'];
     }
     return $user;
 }
Пример #22
0
 /**
  * Vote
  * @author vovich
  * @param unknown_type $model
  * @param unknown_type $modelId
  * @param unknown_type $point
  * @return JSON
  */
 function voting($model, $modelId, $delta)
 {
     Configure::write('debug', 0);
     $this->layout = false;
     $result = array("error" => "", "sum" => 0, "votes_plus" => 0, "votes_minus" => 0);
     $userId = $this->Access->getLoggedUserID();
     if (!$this->RequestHandler->isAjax()) {
         $this->redirect($_SERVER['HTTP_REFERER']);
     }
     if ($userId == VISITOR_USER || !$userId) {
         $result['error'] = "Access error, please login.";
     } elseif (!$this->Access->getAccess('Vote_' . $model, 'c')) {
         $result['error'] = "You can not vote for this " . $model . "<BR> please logg in ";
     } else {
         $result['error'] = $this->Vote->canVote($model, $modelId, $userId);
     }
     $data['model'] = Sanitize::paranoid($model);
     $data['model_id'] = Sanitize::paranoid($modelId);
     $data['user_id'] = $userId;
     $data['delta'] = $delta;
     if (Sanitize::paranoid($model) == 'Image') {
         Cache::delete('last_images');
     } elseif (Sanitize::paranoid($model) == 'Video') {
         Cache::delete('last_images');
     }
     if (empty($result['error'])) {
         $points = $this->Vote->add($data);
         $result['votes_plus'] = $points['votes_plus'];
         $result['votes_minus'] = $points['votes_minus'];
         $result['sum'] = $points['votes_plus'] - $points['votes_minus'];
     }
     exit($this->Json->encode($result));
 }
Пример #23
0
function buildThemes()
{
    global $Site;
    $themes = array();
    $themesPaths = Filesystem::listDirectories(PATH_THEMES);
    foreach ($themesPaths as $themePath) {
        // Check if the theme is translated.
        $languageFilename = $themePath . DS . 'languages' . DS . $Site->locale() . '.json';
        if (!Sanitize::pathFile($languageFilename)) {
            $languageFilename = $themePath . DS . 'languages' . DS . 'en_US.json';
        }
        if (Sanitize::pathFile($languageFilename)) {
            $database = file_get_contents($languageFilename);
            $database = json_decode($database, true);
            $database = $database['theme-data'];
            $database['dirname'] = basename($themePath);
            // --- Metadata ---
            $filenameMetadata = $themePath . DS . 'metadata.json';
            if (Sanitize::pathFile($filenameMetadata)) {
                $metadataString = file_get_contents($filenameMetadata);
                $metadata = json_decode($metadataString, true);
                $database = $database + $metadata;
                // Theme data
                array_push($themes, $database);
            }
        }
    }
    return $themes;
}
 function beforeFilter()
 {
     parent::beforeFilter();
     if (Sanitize::getInt($this->data, 'OwnerReply')) {
         $this->review_id = Sanitize::getInt($this->data['OwnerReply'], 'id');
     } else {
         $this->review_id = Sanitize::getInt($this->params, 'review_id');
     }
     if (!$this->Config->owner_replies || $this->review_id == 0 || $this->_user->id == 0) {
         $this->denyAccess = true;
         return;
     }
     // Get the listing id and extension
     $this->_db->setQuery("\n            SELECT \n                Review.pid AS listing_id, Review.`mode` AS extension\n            FROM \n                #__jreviews_comments AS Review\n            WHERE \n                Review.id = " . $this->review_id);
     // Get listing owner id and check if it matches the current user
     if ($listing = current($this->_db->loadAssocList())) {
         // Automagically load and initialize Everywhere Model to check if user is listing owner
         App::import('Model', 'everywhere_' . $listing['extension'], 'jreviews');
         $class_name = inflector::camelize('everywhere_' . $listing['extension']) . 'Model';
         if (class_exists($class_name)) {
             $this->Listing = new $class_name();
             $owner = $this->Listing->getListingOwner($listing['listing_id']);
             if ($this->_user->id != $owner['user_id']) {
                 $this->denyAccess = true;
                 return;
             }
             $this->data['Listing']['created_by'] = $owner['user_id'];
             // Used in the Activities component
             $this->data['Listing']['listing_id'] = $listing['listing_id'];
             // Used in the Activities component
             $this->data['Listing']['extension'] = $listing['extension'];
             // Used in the Activities component
         }
     }
 }
Пример #25
0
 function saveFeed($filename = "", $view)
 {
     if (Sanitize::getString($this->params, 'action') != 'xml') {
         return false;
     }
     $type = '.' . Sanitize::getString($this->params, 'type', 'rss2');
     $App =& App::getInstance();
     if (!isset($App->jreviewsPaths['Theme'][$this->c->viewTheme][$this->layout][$view . $type . '.thtml']) && !isset($App->jreviewsPaths['Theme']['default'][$this->layout][$view . $type . '.thtml'])) {
         return false;
     }
     $this->c->autoLayout = false;
     $this->c->autoRender = false;
     $rss = array('title' => $this->c->Config->rss_title, 'link' => WWW_ROOT, 'description' => $this->c->Config->rss_description, 'image_url' => WWW_ROOT . "images/stories/" . $this->c->Config->rss_image, 'image_link' => WWW_ROOT);
     $this->c->set(array('encoding' => $this->encoding, 'rss' => $rss));
     $feedFile = fopen($filename, "w+");
     if ($feedFile) {
         $feed = $this->c->render($this->layout, $view . $type);
         fputs($feedFile, $feed);
         fclose($feedFile);
         echo $feed;
         die;
     } else {
         echo "<br /><b>Error creating feed file, please check write permissions.</b><br />";
         die;
     }
 }
Пример #26
0
 public function admin_add()
 {
     $customerdata = $this->User->find("all");
     $this->set('customer_data', $customerdata);
     //pr($customerdata); exit;
     if ($this->request->is('post')) {
         //pr($this->request->data['Fcode']);
         $unique = time();
         $this->request->data['Fcode'] = Sanitize::clean($this->request->data['Fcode'], array("remove_html" => TRUE));
         $productIds = $this->request->data['Fcode']['fcode_product'];
         $productnames = $this->request->data['Fcode']['fcode_product_names'];
         if ($this->Fcode->save($this->request->data['Fcode'])) {
             $arr['FcodeProduct']['fcode_id'] = $fcode_id = $this->Fcode->id;
             $arr['FcodeProduct']['quantity'] = 1;
             for ($i = 0; $i < count($productIds); $i++) {
                 //$this->Product->id = $productIds[$i];
                 $product_q = $this->Product->findById($productIds[$i]);
                 //pr($product_q);exit;
                 $this->Product->id = $productIds[$i];
                 $this->Product->saveField('quantity', $product_q['Product']['quantity'] - 1);
                 $arr['FcodeProduct']['product_id'] = $productIds[$i];
                 $arr['FcodeProduct']['product_name'] = $productnames[$i];
                 $this->FcodeProduct->create();
                 $this->FcodeProduct->save($arr);
             }
             $this->Session->setFlash('<div class="alert alert-success"><i class="fa fa-check-circle"></i> Fcode Details Added Successfully...<button data-dismiss="alert" class="close" type="button">×</button> </div>');
         } else {
             $this->Session->setFlash('<div class="alert alert-fail"><i class="fa fa-check-circle"></i> Fcode Details Not Added Successfully...<button data-dismiss="alert" class="close" type="button">×</button> </div>');
         }
         return $this->redirect(array('action' => 'index'));
     }
 }
Пример #27
0
 function save(&$data)
 {
     $isNew = Sanitize::getInt($data['FieldOption'], 'optionid') ? false : true;
     $field_id = Sanitize::getInt($data['FieldOption'], 'fieldid');
     if ($isNew) {
         // Remove non alphanumeric characters from option value
         $data['FieldOption']['value'] = Sanitize::translate($data['FieldOption']['value']);
         $data['FieldOption']['value'] = str_replace($this->blackList, '', $data['FieldOption']['value']);
         $data['FieldOption']['value'] = str_replace($this->dashReplacements, '-', $data['FieldOption']['value']);
         $data['FieldOption']['value'] = preg_replace(array('/[-]+/'), array('-'), $data['FieldOption']['value']);
         $data['FieldOption']['value'] = mb_strtolower($data['FieldOption']['value'], 'UTF-8');
         // If is new checks for duplicate value
         $query = "SELECT count(fieldid) FROM #__jreviews_fieldoptions WHERE fieldid = '{$field_id}' AND value = " . $this->_db->Quote($data['FieldOption']['value']);
         $this->_db->setQuery($query);
         if ($this->_db->loadResult()) {
             return 'duplicate';
         }
         // Find last option
         $this->_db->setQuery("select max(ordering) FROM #__jreviews_fieldoptions WHERE fieldid = '" . $field_id . "'");
         $max = $this->_db->loadResult();
         if ($max > 0) {
             $data['FieldOption']['ordering'] = $max + 1;
         } else {
             $data['FieldOption']['ordering'] = 1;
         }
     }
     # store it in the db
     if (!$this->store($data)) {
         return 'db_error';
     }
     return 'success';
 }
 function index()
 {
     $module_id = Sanitize::getInt($this->params, 'module_id', Sanitize::getInt($this->data, 'module_id'));
     $this->viewSuffix = Sanitize::getString($this->params['module'], 'tmpl_suffix');
     $cache_file = 'modules_totals_' . $module_id . '_' . md5(serialize($this->params['module']));
     $page = $this->cached($cache_file);
     if ($page) {
         return $page;
     }
     // Initialize variables
     $extension = Sanitize::getString($this->params['module'], 'extension');
     // Automagically load and initialize Everywhere Model
     App::import('Model', 'everywhere_' . $extension, 'jreviews');
     $class_name = inflector::camelize('everywhere_' . $extension) . 'Model';
     $conditions_reviews = array('Review.published = 1');
     $extension == 'com_content' and $conditions_listings = array('Listing.state = 1');
     $extension != '' and $conditions_reviews[] = "Review.mode = " . $this->quote($extension);
     if (class_exists($class_name)) {
         $this->Listing = new $class_name();
         $this->Listing->_user = $this->_user;
         $listings = $this->Listing->findCount(array('conditions' => $conditions_listings), 'DISTINCT Listing.' . $this->Listing->realKey);
         $reviews = $this->Review->findCount(array('conditions' => $conditions_reviews), 'DISTINCT Review.id');
     }
     # Send variables to view template
     $this->set(array('listing_count' => isset($listings) ? $listings : 0, 'review_count' => isset($reviews) ? $reviews : 0));
     $page = $this->render('modules', 'totals');
     # Save cached version
     $this->cacheView('modules', 'totals', $cache_file, $page);
     return $page;
 }
Пример #29
0
 function paginate($term = null, $paginateOptions = array())
 {
     $this->_controller->paginate = array('SearchIndex' => array_merge_recursive(array('conditions' => array(array('SearchIndex.active' => 1), 'or' => array(array('SearchIndex.published' => null), array('SearchIndex.published <= ' => date('Y-m-d H:i:s'))))), $paginateOptions));
     if (isset($this->_controller->request->params['named']['type']) && $this->_controller->request->params['named']['type'] != 'All') {
         $this->_controller->request->data['SearchIndex']['type'] = Sanitize::escape($this->_controller->request->params['named']['type']);
         $this->_controller->paginate['SearchIndex']['conditions']['model'] = $this->_controller->data['SearchIndex']['type'];
     }
     // Add term condition, and sorting
     if (!$term && isset($this->_controller->request->params['named']['term'])) {
         $term = $this->_controller->request->params['named']['term'];
     }
     if ($term) {
         $term = Sanitize::escape($term);
         $this->_controller->request->data['SearchIndex']['term'] = $term;
         $term = implode(' ', array_map(array($this, 'replace'), preg_split('/[\\s_]/', $term))) . '*';
         if ($this->like) {
             $this->_controller->paginate['SearchIndex']['conditions'][] = array('or' => array("MATCH(data) AGAINST('{$term}')", 'SearchIndex.data LIKE' => "%{$this->_controller->data['SearchIndex']['term']}%"));
         } else {
             $this->_controller->paginate['SearchIndex']['conditions'][] = "MATCH(data) AGAINST('{$term}' IN BOOLEAN MODE)";
         }
         $this->_controller->paginate['SearchIndex']['fields'] = "*, MATCH(data) AGAINST('{$term}' IN BOOLEAN MODE) AS score";
         if (empty($this->_controller->paginate['SearchIndex']['order'])) {
             $this->_controller->paginate['SearchIndex']['order'] = "score DESC";
         }
     }
     return $this->_controller->paginate('SearchIndex');
 }
 public static function save($value, $type, $standard = null)
 {
     $var = $standard;
     if ($value !== null) {
         if ($type == VAR_DB || $type == VAR_ARR_DB) {
             $var = Sanitize::saveDb($value);
         } elseif ($type == VAR_HTML || $type == VAR_ARR_HTML) {
             $var = Sanitize::saveHTML($value);
         } elseif ($type == VAR_INT || $type == VAR_ARR_INT) {
             $var = Sanitize::saveInt($value);
         } elseif ($type == VAR_ALNUM || $type == VAR_ARR_ALNUM) {
             $var = Sanitize::saveAlNum($value, true);
         } elseif ($type == VAR_URI || $type == VAR_ARR_URI) {
             $var = Sanitize::saveAlNum($value, false);
         } else {
             $var = Sanitize::removeNullByte($value);
         }
     } else {
         if ($standard === null) {
             if ($type == VAR_DB || $type == VAR_ALNUM || $type == VAR_HTML || $type == VAR_URI) {
                 $var = '';
             } elseif ($type == VAR_INT) {
                 $var = 0;
             } elseif ($type == VAR_ARR_INT || $type == VAR_ARR_DB || $type == VAR_ARR_ALNUM || $type == VAR_ARR_NONE || $type == VAR_ARR_HTML || $type == VAR_ARR_URI) {
                 $var = array();
             } else {
                 $var = null;
             }
         }
     }
     return $var;
 }