Exemplo n.º 1
0
 /**
  * 
  * @param PCModelWebsite $site
  * @param PCModelUser $user
  * @param string $comment
  * @param string $usability
  * @param string $contents
  * @param string $reliability
  * @param string $language
  * @param string $error
  * @return bool
  */
 public static function addReviewForSite($site, $user, $comment, $usability, $contents, $reliability, $language, &$error) {
     if (!isset($site) || !isset($site)){
         die("Internal Inconsistency");
     }
     
     if(!PCHelperValidator::validateLanguageCode($language)){
         $error = "Invalid language code";
         return FALSE;
     }
     $language = strtoupper($language);
     $commentLen = strlen($comment);
     if ($commentLen < 5 || $commentLen > PCModelReview::maxCommentLength) {
         
         $error = "Invalid comment length, ".( ($commentLen < 5) ? " minumum length is 6 characters" : "maximum length is 200 characters");
         return FALSE;
     }
     
     $usa = floatval($usability);
     $cont = floatval($contents);
     $rel = floatval($reliability);
     
     if($usa < PCModelReview::minVote ||$usa > PCModelReview::maxVote){
         $error = "usability is not valid";
         return FALSE;
     }
     if($cont < PCModelReview::minVote ||$cont > PCModelReview::maxVote){
          $error = "contents is not valid";
         return FALSE;
     }
     if($rel < PCModelReview::minVote ||$rel > PCModelReview::maxVote){
          $error = "reliability is not valid";
         return FALSE;
     }
     
     $date_added = new DateTime('now', new DateTimeZone('UTC'));
     $date_added_mysql = $date_added->format('Y-m-d H:i:s');
     
     $values = array(
         'site_identifier' => $site->getIdentifier(),
         'user_identifier' => $user->getIdentifier(),
         'comment' => $comment,
         'usability' => $usa,
         'reliability' => $rel,
         'contents' => $cont,
         'language_code' => $language,
         'date_added' => $date_added_mysql
     );
     
     if($user->getAccountType() !== PCModelUser::$TYPE_DEFAULT && PCConfigManager::sharedManager()->getBoolValue('SOCIAL_POST_ON_REVIEW') ){
         $user->postReviewToTimeline($values,$site);
     }
     
     $dupUpdate = array('language_code','date_added','contents','reliability','usability','comment');
     
     if(PCModelManager::insertObject(PCModelReview::getMapper(), $values, $dupUpdate)){
         return TRUE;
     }
     $error = "Error adding review please try later";
     return FALSE;
 }
 /**
  * 
  * @param PCRequest $request
  * @param PCModelApplication $application
  * @return bool
  */
 public function doLogin($request, $application)
 {
     $param = $request->getParams();
     $userName = $param['uname'];
     $pwd = $param['pwd'];
     $keys = array('username' => $userName, "account_type" => PCModelUser::$TYPE_DEFAULT);
     $user_array = PCModelManager::fetchModelObjectInstances(PCModelUser::getMapper(), $keys, NULL, TRUE);
     $user = $user_array[0];
     if (isset($user) && strcmp($pwd, $user->getPassword()) == 0) {
         $secret = $application->getAppSecret();
         $appId = $application->getIdentifier();
         $time = time();
         $cookieValue = PCAuth::computeHashForString($userName . $time . $secret);
         $distantFuture = PCResponseCookie::getDistantFuture();
         if (PCMapperToken::setTokenForUserWithIdentifier($user->getIdentifier(), $appId, $cookieValue, $distantFuture)) {
             $_SESSION['user'] = $this->user_id = $user->getIdentifier();
             $presence_cookie = PCResponseCookie::lifetimeCookie("presence_c", $cookieValue);
             //setcookie("presence_c", $cookieValue, $expirationTime,"/");
             $user_cookie = PCResponseCookie::lifetimeCookie("user", $user->getIdentifier());
             //setcookie("user",$user->getIdentifier(), $expirationTime,"/");
             $response = PCResponse::currentResponse();
             $response->addCookie($presence_cookie);
             $response->addCookie($user_cookie);
         } else {
             return FALSE;
         }
         return TRUE;
     }
     return FALSE;
 }
Exemplo n.º 3
0
        /**
     * @param PCRequest $request
     */
    public function profileAction($request) {

        $auth = $request->getAuthHandler();
        $auth->authorize();
         $params = $request->getParams();
        
       

        if (isset($params['id']) && $auth->isAuthorized() && (strcmp($params['id'], $auth->getUserIdentifier()) == 0)) {

            $result = array();
            $user = PCModelUser::getCurrentUser();

            $result['username'] = $user->getUsername();
            $result['name'] = $user->getName();
            $result['surname'] = $user->getSurname();
            $result['member_since'] = $user->getCreation_date()->format("Y-m-d");
            $result['user_id'] = $user->getIdentifier();
            $result['email'] = $user->getEmail();
            $result['title'] = "WebSherpa - " . $user->getUsername();
            return PCRendererHTML::rendererForView('user', $result);
        }


        return null;
    }
Exemplo n.º 4
0
    /**
     * Setta i cookie dell'utente
     * @param PCModelUserOauth $user
     * @return boolean
     */
    private function authorizeUser($user) {
        if(isset($user) === FALSE) return FALSE;
        $_SESSION['user'] = $user->getIdentifier();

        $secret = $this->application->getAppSecret();
        $appId = $this->application->getIdentifier();
        $time = time();
        $cookieValue = PCAuth::computeHashForString($user->getUsername() . $time . $secret);
        $distantFuture = PCResponseCookie::getDistantFuture();

        if (PCMapperToken::setTokenForUserWithIdentifier($user->getIdentifier(), $appId, $cookieValue, $distantFuture)) {

            $_SESSION['user'] = $user->getIdentifier();

            $presence_cookie = PCResponseCookie::lifetimeCookie("presence_c", $cookieValue);
            $user_cookie = PCResponseCookie::lifetimeCookie("user", $user->getIdentifier());

            $response = PCResponse::currentResponse();
            $response->addCookie($presence_cookie);
            $response->addCookie($user_cookie);
            PCModelUser::setCurrentUser($user);
            return TRUE;
        }
        return FALSE;
    }
Exemplo n.º 5
0
 public function contactAction($request)
 {
     $attributes = $request->getParams();
     $name = $attributes['name'];
     $email = $attributes['email'];
     $object = $attributes['object'];
     $text = $attributes['text'];
     $challenge = $attributes['recaptcha_challenge_field'];
     $response = $attributes['recaptcha_response_field'];
     if (!isset($name) || !isset($email) || !isset($object) || !isset($text)) {
         return new PCRendererJSON(array("error" => "Please check fields!!!"), 200);
     }
     require_once __EXTERNAL_LIBRARIES__ . '/recaptcha/recaptchalib.php';
     $privatekey = "6Lfm39cSAAAAAFpyN0tQr4TYNt1zqiaHn9E22lYb";
     $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $challenge, $response);
     if (!$resp->is_valid) {
         // What happens when the CAPTCHA was entered incorrectly
         error_log($resp->error);
         return new PCRendererJSON(array("error" => "Incorrect Captcha"));
     }
     $user = PCModelUser::getCurrentUser();
     $attributes['user'] = $user;
     $mail = PCEmailBuilder::buildContactUsEmail($attributes);
     PCEmailSender::sendMail($mail);
     return new PCRendererJSON(array("result" => "Ok"));
 }
Exemplo n.º 6
0
 function __construct($result, $templateName, $pages, $scripts = NULL, $styleSheets = NULL)
 {
     parent::__construct($result);
     $user = PCModelUser::getCurrentUser();
     if (isset($user)) {
         $this->result['user'] = $user;
     }
     $this->scripts = $scripts == NULL ? array() : $scripts;
     $this->styleSheets = $styleSheets == NULL ? array() : $styleSheets;
     $this->templateName = $templateName;
     $this->pages = $pages;
 }
Exemplo n.º 7
0
    /**
     * @param PCRequest $request
     */
    public function facebookCallbackAction($request) {
        PCAutoloader::importLibrary('facebook');
        $facebook = new Facebook(array(
            "appId" => FB_APP_ID,
            "secret" => FB_APP_SECRET,
            "cookie" => true
        ));
        $params = $request->getParams();
        $user_profile = NULL;
        
        try {
            $user = $facebook->getUser();
            if (isset($user)) {
                $user_profile = $facebook->api('/me');      
            }
        } catch (FacebookApiException $e) {
            c_dump($_GET);
            error_log("AAAA".$e);
            throw new PCExceptionRedirection("/page/register");
        }
        
        if (isset($params['reg_username'])){
            
            if (PCMapperUser::validateUsername($params['reg_username']) == FALSE) {
                $cont = array("title" => "WebSherpa - Insert Username", "text_error" => "Insert a valid Username; min 6 characters use only characters and numbers and \"_\"", "show_email" => TRUE);
                return PCRendererHTML::rendererForView('insertUname', $cont);
            }

            if (count(PCModelManager::fetchModelObjectInstances(PCModelUser::getMapper(), array("username" => $params['reg_username']))) != 0) {
                $cont = array("title" => "WebSherpa - Insert Username", "text_error" => "Username already used, please choose another username.", "show_email" => TRUE);
                return PCRendererHTML::rendererForView('insertUname', $cont);
            }
            
            $adapter = new PCHelperSocialAdapterFacebook($facebook, $user_profile, $params['reg_username']);
            if($request->getAuthHandler()->authorizeOauthUser($adapter)){
                throw new PCExceptionRedirection("/");
            }
            throw new PCExceptionRedirection("/page/register");
        }
        else{
            
            $adapter = new PCHelperSocialAdapterFacebook($facebook, $user_profile);
            if($request->getAuthHandler()->authorizeOauthUser($adapter) === FALSE){
                
                return PCRendererHTML::rendererForView('insertUname', array("title" => "WebSherpa - Insert Username"));
            }
            
            throw new PCExceptionRedirection("/");
        }
        
    }
Exemplo n.º 8
0
    /**
     * XXX evitare utilizzo diretto del database
     * @param array $attributes
     * @param string $error
     * @return boolean
     */
    public static function createUserWithAttributes($attributes, &$error) {
        $username = $attributes['username'];
        $name = $attributes['name'];
        $surname = $attributes['surname'];
        $email = $attributes['email'];
        $password = $attributes['password'];

        if (static::validateName($name) == false) {
            $error = "Invalid name";
            return false;
        }
        if (static::validateSurname($surname) == false) {
            $error = "Invalid surname";
            return false;
        }
        if (static::validateUsername($username) == FALSE) {
            $error = "username is not valid (min 5, max 20 chars)";
            return false;
        }
        if (static::validateMail($email) == FALSE) {
            $error = "email already registered";
            return FALSE;
        }

        $mapper = PCModelUser::getMapper();

        $pdo = PCDatabase::getSharedDatabaseConnection();

        $select = "SELECT username ,email FROM " . $mapper->getTableForInsertUpdate() . " WHERE (username = :uname OR email = :mail) AND account_type = :type;";
        $prepared = $pdo->prepare($select);

        if ($prepared === FALSE) {
            c_dump($prepared->errorInfo());
            return FALSE;
        }

        $result = $prepared->execute(array(':uname' => $username, ':mail' => $email, ':type' => PCModelUser::$TYPE_DEFAULT));

        if ($result === FALSE) {
            ob_start();
            print_r($prepared->errorInfo());
            $prepared->debugDumpParams();
            $contents = ob_get_contents();
            ob_end_clean();
            error_log($contents);
            return FALSE;
        }

        while ($item = $prepared->fetch(PDO::FETCH_ASSOC)) {

            if (strcmp($item['email'], $email) == 0) {
                $error = "email already registered";
                return FALSE;
            } else if (strcmp($item['username'], $username) == 0) {
                $error = "username already registered";
                return FALSE;
            }
        }

        $date = new DateTime('now', new DateTimeZone('UTC'));
        

        $keys = array(
            'creation_date' => $date->format('Y-m-d H:i:s'),
            'username' => $username,
            'penalities' => '0',
            'surname' => $surname,
            'name' => $name,
            'email' => $email,
            'password' => $password
        );



        return PCModelManager::insertObject($mapper, $keys);
    }
Exemplo n.º 9
0
     /**
     * Crea una nuova password(aggiorna il db) e la restituisce. restituisce false in caso negativo
     * @param PCModelUser $user_id l' id dell' utente
     * @param string $hash l' hash inviato dall'utente
     * @param PCModelUser
     * @return boolean|string
     */
    public static function handleRepassRequest($user_id, $hash, &$user_to_ret) {
        $keys = array('request_hash'=>$hash, 'user_id'=>$user_id);
        $items = PCModelManager::fetchModelObjectInstances(PCModelRepass::getMapper(), $keys, NULL, TRUE);
        if (count($items) <= 0) {
            return FALSE;
        }

        $item = $items[0];

        if ($item == NULL || $item->isExpired()) {
            c_dump("SCADUTA");
            return FALSE;
        }

        $bindigngs = array(":h" => $hash, ":user"=> $user_id);
        
        PCModelManager::deleteObject(PCModelRepass::getMapper(), "request_hash = :h AND user_id = :user", $bindigngs);
        
        $newPwd = PCMapperRepass::rand_password(8); 
        

        $model_user = PCModelManager::fetchObjectWithIdentifier(PCModelUser::getMapper(), $item->getUser_id(), NULL, TRUE);
        
        
        if($model_user == NULL){
            $id = $item->getUser_id();
            error_log("User non presente (user_id: $id )");
            return FALSE;
        }
        
        $newPwdHash = PCAuth::computeHashForString($newPwd);
        
        if(PCMapperUser::changePasswordForUser($model_user, $newPwdHash) == FALSE){
            return FALSE;
        }
        $user_to_ret = $model_user;
        return $newPwd;
        
    }
Exemplo n.º 10
0
    /**
     * Restituisce l'utente connesso attualmente (se disponibile)
     * @return ModelUser 
     */
    public static function getCurrentUser(){
        if(static::$current_user != NULL) return static::$current_user;
        

        if(isset(static::$current_user_identifier)){
            $user = PCModelManager::fetchObjectWithIdentifier(PCModelUser::getMapper(), static::$current_user_identifier, NULL, TRUE);
            
            static::$current_user = $user;
            
            
            return $user;
        }
        
        return NULL;
    }
Exemplo n.º 11
0
    /**
     * 
     * @param PCRequest $request
     */
    public function siteAction($request) {
        $param = $request->getParams();

        $hostName = $request->dequeuePathComponent();
        if (isset($hostName)) {
            $site = PCMapperWebsite::getSiteWithDomain($hostName);
            if (isset($site) == FALSE) {
                throw new PCExceptionController("Page not found", 404);
            }
            $identifier = $site->getIdentifier();
            throw new PCExceptionRedirection("/sites/site?id=$identifier");
        }


        if (isset($param['id']) == FALSE)
            throw new PCExceptionController("Page not found", 404);
        /** @value  PCModelWebsite $site */
        $site = PCModelManager::fetchObjectWithIdentifier(PCModelWebsite::getMapper(), $param['id'], NULL, TRUE);

        if (!isset($site)) {
            throw new PCExceptionController("Page not found", 404);
        }

        if ($site->cacheIsExpired()) {
            $site = PCMapperWebsite::recacheSiteReview($site);
            if (isset($site) == FALSE) {
                throw new PCExceptionController('Error caching', 500);
            }
        }

        $result = array();

        $result['siteCategory'] = PCMapperCategory::nameFromIdentifier($site->getCategory());
        $result['site_id'] = $site->getIdentifier();
        $result['siteHost'] = $site->getUrl();

        $result['reliability'] = $site->getReliability();
        $result['contents'] = $site->getContents();
        $result['usability'] = $site->getUsability();

        $result['averageVote'] = $site->getVote();
        $result['votesCount'] = $site->getNumber_of_votes();
        $result['dateAdded'] = $site->getDate_added()->format("Y-m-d");

        $reviews = PCMapperReview::getReviewsWithSiteIdentifier($site->getIdentifier(), 0);
        $reviewsList = array();

        foreach ($reviews as $r) {
            $reviewArray = array();
            $reviewArray["vote"] = sprintf("%.1f", $r->getVote());

            $user = PCModelManager::fetchObjectWithIdentifier(PCModelUser::getMapper(), $r->getUserIdentifier(), NULL, TRUE);

            $reviewArray["user"] = $user->getUsername();
            $reviewArray["date_added"] = $r->getDate_added()->format("Y-m-d");
            $reviewArray["comment"] = $r->getComment();
            $reviewArray["reviewId"] = $r->getIdentifier();
            $reviewArray["userId"] = $r->getUserIdentifier();
            $reviewArray['reliability'] = sprintf("%.1f", $r->getReliabilityVote());
            $reviewArray['contents'] = sprintf("%.1f", $r->getContentsVote());
            $reviewArray['usability'] = sprintf("%.1f", $r->getUsabilityVote());
            $reviewsList[] = $reviewArray;
        }

        $result['reviews'] = $reviewsList;


        $result['title'] = "WebSherpa - " . $site->getUrl();
        return PCRendererHTML::rendererForView('host', $result);
    }
Exemplo n.º 12
0
    /**
     * 
     * @param PCHelperSocialAdapter $service_adapter
     * @return PCModelUserOauth
     */
    public static function getOauthUserWithIdentifier($service_adapter) {
        $keys = array(
            "oauth_provider" => $service_adapter->getServiceType(),
            "oauth_uid" => $service_adapter->getServiceUserIdentifier()
        );
        $instances = PCModelManager::fetchModelObjectInstances(PCModelUserOauth::getMapper(), $keys);
        if (count($instances) == 0)
            return NULL;

        $result = $instances[0];

        if(isset($result['oauth_uid']) && $result['user_identifier'] == '0') return FALSE;
        
        $user = PCModelManager::fetchObjectWithIdentifier(PCModelUser::getMapper(), $result['user_identifier'], NULL, TRUE);
        if (isset($user)) {
            
            $bindings = array(
                "oauth_token" =>  $service_adapter->getTokenValue(),
                "oauth_secret" => $service_adapter->getSecretValue(),
            );

            if( PCModelManager::updateObject(PCModelUserOauth::getMapper(), $bindings, "identifier = :iddd",array(":iddd"=>$result['identifier'])) === FALSE) return NULL; 
            
            $service_adapter->addOauthInfoToUser($user);
        }
        return $user;
    }
Exemplo n.º 13
0
    /**
     * Restituisce le recensioni legate ad un sito oppure ad un utente
     * @param PCRequest $request
     */
    public function getSiteReviewsAction($request) {
        $params = $request->getParams();
        
        if( isset($params['offset']) == FALSE) return new PCRendererJSON(array("error" => "missing param 'offset'"), 400);
        
        $offset = $params['offset'];
        
        if( isset($params['site_id'])){
            $site_id = $params['site_id'];
            
            $result = array();
            
            $reviews = PCMapperReview::getReviewsWithSiteIdentifier($site_id, $offset);
           
            foreach ($reviews as $r) {
                $tmp = array();
                $tmp["vote"] = sprintf("%.1f", $r->getVote());
                //XXX pensare ad un modo più efficente per risolvere gli identificativi
                $user = PCModelManager::fetchObjectWithIdentifier(PCModelUser::getMapper(), $r->getUserIdentifier(), NULL, TRUE);
                $tmp["user"] = $user->getUsername();
                $tmp["date_added"] = $r->getDate_added()->format("Y-m-d");
                $tmp["comment"] = $r->getComment();
                $tmp["reviewId"] = $r->getIdentifier();
                $tmp["userId"] = $user->getIdentifier();
                $tmp['reliability'] = sprintf("%.1f", $r->getReliabilityVote());
                $tmp['contents'] = sprintf("%.1f", $r->getContentsVote());
                $tmp['usability'] = sprintf("%.1f", $r->getUsabilityVote());
                $result[] = $tmp;
            }
            return new PCRendererJSON($result);
        }
        
        if (isset($params['user_id'])) {
            $user_id = $params['user_id'];
            $result = array();

            $user = PCModelManager::fetchObjectWithIdentifier(PCModelUser::getMapper(), $user_id, NULL, TRUE);
            if (!isset($user))
                new PCRendererJSON(array("error" => "wrong user identifier"), 400);

           // $user_name = $user->getUsername();

            $reviews = PCMapperReview::getReviewsWithUserIdentifier($user_id, $offset);
           
            foreach ($reviews as $r) {
                $tmp = array();
                
                //XXX pensare ad un modo più efficente per risolvere gli identificativi
                $site = PCModelManager::fetchObjectWithIdentifier(PCModelWebsite::getMapper(), $r->getSiteIdentifier(), NULL, TRUE);

                $tmp["vote"] = sprintf("%.1f",$r->getVote());
                $tmp["site"] = $site->getDomain();
                $tmp["date_added"] = $r->getDate_added()->format("Y-m-d");
                $tmp["comment"] = $r->getComment();
                $tmp["reviewId"] = $r->getIdentifier();
                $tmp["siteId"] = $site->getIdentifier();
                $tmp['reliability'] = sprintf("%.1f",$r->getReliabilityVote());
                $tmp['contents'] = sprintf("%.1f",$r->getContentsVote());
                $tmp['usability'] = sprintf("%.1f",$r->getUsabilityVote());
                $result[] = $tmp;
            }
            return new PCRendererJSON($result);
        }

        return new PCRendererJSON(array("error" => "missing param 'site_id' or 'user_id"), 400);
    }