コード例 #1
0
ファイル: VciApiController.php プロジェクト: skafetzo/SPtool
 public function show($username)
 {
     $user = MecanexUser::where('username', $username)->get()->first();
     if (empty($user)) {
         $response = ["error" => "User doesn`t exist"];
         $statusCode = 404;
     } else {
         $terms = $user->profilescore;
         foreach ($terms as $term) {
             $user_profile = [];
             $temp[$term['term']] = $term['pivot']['profile_score'];
             array_push($user_profile, $temp);
         }
         $response = $user_profile;
         $statusCode = 200;
     }
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #2
0
 public function recommend($username)
 {
     //this assumes that the input is of type videos=EUS_025A722EA4B240D8B6F6330A8783143C,EUS_00A5E7F2D522422BB3BF3BF611CAB22F
     //however according to the input decided proper adjustments have to be made bearing in mind that where in expects string, e.g. 'a',b'
     $user = MecanexUser::where('username', $username)->get()->first();
     if (empty($user)) {
         $response = ["error" => "User doesn`t exist"];
         $statusCode = 404;
     } else {
         $user_id = $user->id;
         //parameter for the experiment
         $neighs = '2';
         $list_neighs = [];
         //content_based recommendation -- using the view
         $results_content = DB::select(DB::raw('select  video_id, title, similarity FROM user_item_similarity where user=?  GROUP BY video_id, title ORDER BY similarity DESC LIMIT 10'), [$user_id]);
         //collaborative recommendation
         //			//multiplies vector of user i with every one of its neighbors and sorts them in descending order
         $results_neighs = DB::select(DB::raw('select neighbor FROM user_neighbor_similarity where user=? ORDER BY similarity DESC LIMIT ?'), [$user_id, $neighs]);
         foreach ($results_neighs as $neigh) {
             array_push($list_neighs, $neigh->neighbor);
         }
         if (empty($list_neighs)) {
             //content recommendation if no neighbors
             $results_recommendation = $results_content;
         } else {
             $string_neighs = implode(',', $list_neighs);
             $results_recommendation = DB::select(DB::raw(' SELECT a.user,a.video_id,user_item_similarity.title, user_item_similarity.euscreen_id, (0.8*user_item_similarity.similarity+0.2*a.score) as result from (SELECT  user_neighbor_similarity.user,user_item_similarity.video_id, SUM(user_neighbor_similarity.similarity+user_item_similarity.similarity) as score FROM user_neighbor_similarity INNER JOIN user_item_similarity on user_neighbor_similarity.neighbor=user_item_similarity.user and user_item_similarity.user IN(' . $string_neighs . ') GROUP BY user_neighbor_similarity.user,user_item_similarity.video_id) as a INNER JOIN user_item_similarity on a.video_id = user_item_similarity.video_id and a.user=user_item_similarity.user where a.user=? ORDER BY score DESC LIMIT 10'), [$user_id]);
         }
         $final_results = [];
         foreach ($results_recommendation as $result) {
             array_push($final_results, $result->euscreen_id);
         }
         $response = ["Video Ids" => $final_results];
         $statusCode = 200;
     }
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #3
0
 private function recommend_enr($list, $user_id)
 {
     $terms = Term::all();
     $user = MecanexUser::where('id', $user_id)->get()->first();
     $user_terms_scores = $user->profilescore;
     foreach ($user_terms_scores as $user_term_score) {
         $temp_profile_scores[] = $user_term_score->pivot->profile_score;
     }
     foreach ($list as $enrichment) {
         $arithmitis = 0;
         $sumA = 0;
         $sumB = 0;
         $temp_enrichment_scores = [];
         $enrichment_terms_scores = DB::select(DB::raw('SELECT * FROM enrichments_terms_scores WHERE enrichment_id=? ORDER BY term_id'), [$enrichment["enrichment_id"]]);
         foreach ($enrichment_terms_scores as $enrichment_term_score) {
             $temp_enrichment_scores[] = $enrichment_term_score->enrichment_score;
         }
         for ($i = 0; $i < count($terms); $i++) {
             $arithmitis = $arithmitis + $temp_enrichment_scores[$i] * $temp_profile_scores[$i];
             $sumA = $sumA + pow($temp_enrichment_scores[$i], 2);
             $sumB = $sumB + pow($temp_profile_scores[$i], 2);
         }
         $enrichment["score"] = $arithmitis / (sqrt($sumA) + sqrt($sumB));
         $enrichmentScores[$enrichment["enrichment_id"]] = $arithmitis / (sqrt($sumA) + sqrt($sumB));
     }
     arsort($enrichmentScores);
     return $enrichmentScores;
     //		// first key of enrichmentScores list - the most recommended enrichment
     //		$recommended_enrichment = key($enrichmentScores);
     //
     //		return Enrichment::find($recommended_enrichment)->enrichment_id;
 }
コード例 #4
0
 /**
  * Update the specified resource in storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function update(InterestRequest $request, $username)
 {
     $interests = $request->except('_method');
     $user = MecanexUser::where('username', $username)->get()->first();
     if (empty($user)) {
         $response = ["error" => "User doesn`t exist"];
         $statusCode = 404;
     } elseif (count($user->interest) == 0) {
         $response = ["message" => "User has not set any interests, To create interests, try store"];
         $statusCode = 404;
     } else {
         //check if what sends is correct or else it crushes
         //updates interests and user scores
         $key_values = array();
         foreach ($interests as $key => $value) {
             $interest = Interest::where('short_name', $key)->get(array('id'))->first();
             $key_values[$interest->id] = $value;
             $user->interest()->sync([$interest->id => ['interest_score' => $value]], false);
             $term = Term::where('term', $key)->firstOrFail();
             $value = $value / 5;
             $user->term()->sync([$term->id => ['user_score' => $value]], false);
         }
         //there must be a more clever way to do this (foreach maybe)
         //created 2 arrays one with the term ids ($term_ids) and the other with the scores ($term_scores)
         $terms = Term::get(array('id'));
         $all_terms = [];
         foreach ($terms as $term) {
             array_push($all_terms, $term->id);
         }
         $all_terms_length = count($all_terms);
         ksort($key_values);
         $term_ids = array_keys($key_values);
         $term_ids_length = count($term_ids);
         //update adjacency matrix
         for ($i = 0; $i <= $term_ids_length - 1; $i++) {
             for ($j = 0; $j <= $all_terms_length - 1; $j++) {
                 if ($term_ids[$i] == $all_terms[$j]) {
                     continue;
                 } elseif ($term_ids[$i] > $all_terms[$j]) {
                     $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $all_terms[$j])->where('term_neighbor_id', $term_ids[$i])->get()->first();
                     $temp_user = $user->term->find($all_terms[$j]);
                     $user_term_score_a = $temp_user->pivot->user_score;
                     $temp_user = $user->term->find($term_ids[$i]);
                     $user_term_score_b = $temp_user->pivot->user_score;
                     $new_score = $user_term_score_b * $user_term_score_a;
                     //						}
                 } else {
                     $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $term_ids[$i])->where('term_neighbor_id', $all_terms[$j])->get()->first();
                     $temp_user = $user->term->find($all_terms[$j]);
                     $user_term_score_a = $temp_user->pivot->user_score;
                     $temp_user = $user->term->find($term_ids[$i]);
                     $user_term_score_b = $temp_user->pivot->user_score;
                     $new_score = $user_term_score_b * $user_term_score_a;
                 }
                 $temp_user_matrix->link_score = $new_score;
                 $temp_user_matrix->save();
             }
         }
         //update profile
         for ($j = 1; $j <= $all_terms_length; $j++) {
             $profile_score = 0;
             for ($i = 1; $i <= $all_terms_length; $i++) {
                 $temp_user = $user->term->find($i);
                 $user_term_score = $temp_user->pivot->user_score;
                 //get score of user
                 if ($i == $j) {
                     $link_score = 0;
                 } elseif ($i > $j) {
                     $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $j)->where('term_neighbor_id', $i)->get()->first();
                     $link_score = $temp_user_matrix->link_score;
                 } else {
                     $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $i)->where('term_neighbor_id', $j)->get()->first();
                     $link_score = $temp_user_matrix->link_score;
                 }
                 $profile_score = $profile_score + $user_term_score * $link_score;
             }
             $user->profilescore()->sync([$j => ['profile_score' => $profile_score]], false);
         }
         $response = ["message" => "User Interests were saved"];
         $statusCode = 201;
     }
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #5
0
 public function destroy($username)
 {
     //
     $mecanexuser = MecanexUser::where('username', $username)->get()->first();
     if (empty($mecanexuser)) {
         $response = ["error" => "User doesn`t exist"];
         $statusCode = 404;
     } else {
         //
         $mecanexuser->delete();
         $statusCode = 200;
         $response = ["message" => "User deleted"];
     }
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #6
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function login(Request $request, SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
 {
     //test if token for FB login is enough
     $token = $request->token;
     //	return $token;
     // does not work since $token is string but should be token
     //		if (! $token->isLongLived()) {
     //			// OAuth 2.0 client handler
     //			$oauth_client = $fb->getOAuth2Client();
     //
     //			// Extend the access token.
     //			try {
     //				$token = $oauth_client->getLongLivedAccessToken($token);
     //			} catch (Facebook\Exceptions\FacebookSDKException $e) {
     //				dd($e->getMessage());
     //			}
     //		}
     //this is for not include $token in the get calls
     $fb->setDefaultAccessToken($token);
     // Get basic info on the user from Facebook.
     try {
         $response = $fb->get('/me?fields=id,email');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     try {
         $profileresponse = $fb->get('/me?fields=id,name,gender');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     // Convert the response to a `Facebook/GraphNodes/GraphUser` collection
     $facebook_user = $response->getGraphUser();
     $mecanex_user = $profileresponse->getGraphUser();
     // Create the user if it does not exist or update the existing entry.
     // This will only work if you've added the SyncableGraphNodeTrait to your User model.
     $user = User::createOrUpdateGraphNode($facebook_user);
     //store profile data in mecanex_users table
     $id = $user->id;
     $facebook_id = $user->facebook_user_id;
     $fullname = $mecanex_user->getName();
     $fullname = explode(" ", $fullname);
     $name = $fullname[0];
     $surname = $fullname[1];
     $gender = $mecanex_user->getGender();
     if ($gender == 'female') {
         $gender_id = 2;
     } else {
         $gender_id = 1;
     }
     $fbuser = MecanexUser::firstOrNew(array('facebook_user_id' => $facebook_id));
     $fbuser->user_id = $id;
     $fbuser->facebook_user_id = $facebook_id;
     $fbuser->gender_id = $gender_id;
     $fbuser->name = $name;
     $fbuser->surname = $surname;
     $fbuser->save();
     // Log the user into Laravel
     Auth::login($user);
     // create records in table users_terms-scores once a mecanex user has been created
     $terms = Term::all();
     foreach ($terms as $term) {
         $fbuser->term()->sync([$term->id => ['user_score' => 0]], false);
     }
     $response = 'User was saved';
     $statusCode = 201;
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #7
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function target(Request $request)
 {
     try {
         $mecanexusers = MecanexUser::all();
         // filter by demographics
         if ($request->gender_id != 0) {
             $mecanexusers = $mecanexusers->where("gender_id", (int) $request->gender_id);
         }
         if ($request->age_id != 0) {
             $mecanexusers = $mecanexusers->where("age_id", (int) $request->age_id);
         }
         if ($request->education_id != 0) {
             $mecanexusers = $mecanexusers->where("education_id", (int) $request->education_id);
         }
         if ($request->occupation_id != 0) {
             $mecanexusers = $mecanexusers->where("occupation_id", (int) $request->occupation_id);
         }
         if ($request->country_id != 0) {
             $mecanexusers = $mecanexusers->where("country_id", (int) $request->country_id);
         }
         // filter by preference on terms
         // keep mecanex users whose term profile score is more than 0.7 when normalized by the max term value of the user
         $statusCode = 200;
         if ($request->terms != []) {
             $all_terms = Term::all();
             foreach ($all_terms as $term) {
                 if (strpos($request->terms, $term->term) !== false) {
                     $mecanexusers = $mecanexusers->filter(function ($user) use($term) {
                         $myquery = DB::select(DB::raw(' SELECT MAX(profile_score) as mymax
                                                        FROM users_terms_profilescores
                                                        WHERE mecanex_user_id=' . $user->id . ''));
                         if ($myquery[0]->mymax == 0) {
                             // don't take into account users that have not provided any information
                             return false;
                         }
                         return $user->profilescore[$term->id - 1]['pivot']['profile_score'] / $myquery[0]->mymax > 0.7;
                         // minus one because terms start from 0 where id starts from 1
                     });
                     //                        $response[] = $mecanexusers[1]->profilescore[$term->id-1]['pivot']['profile_score'];
                     //                        $myquery = DB::select(DB::raw(' SELECT MAX(profile_score) as mymax
                     //                                                           FROM users_terms_profilescores
                     //                                                           WHERE mecanex_user_id='. $mecanexusers[2]->id .''));
                 }
             }
         }
         $array_of_users = array();
         // If no mecanexusers exist from the filters selected, we return a random list of videos
         if ($mecanexusers->isEmpty()) {
             $response = [];
             $response['message'][] = "No information for the target group";
             $statusCode = 200;
             return $response;
         }
         foreach ($mecanexusers as $mecanexuser) {
             $array = array();
             $terms = $mecanexuser->profilescore;
             foreach ($terms as $term) {
                 $temp = (double) $term['pivot']['profile_score'];
                 array_push($array, $temp);
             }
             // normalize with maximum because that way the clustering seems more accurate
             $maximum = max($array);
             if ($maximum != 0) {
                 for ($i = 0; $i < count($array); $i++) {
                     $array[$i] = $array[$i] / $maximum;
                 }
             }
             array_push($array_of_users, $array);
         }
         /** return the array of users so that we can see whether the profiles have normalized
          * values so that they can be clustered properly
          */
         $space = new Space(14);
         $num_of_clusters = 5;
         foreach ($array_of_users as $point) {
             $space->addPoint($point);
         }
         $clusters = $space->solve($num_of_clusters);
         $all_users = [];
         //            foreach ($clusters as $i => $cluster)
         //                printf("Cluster %d [%d,%d]: %d points\n", $i, $cluster[0], $cluster[1], count($cluster));
         foreach ($clusters as $i => $cluster) {
             $terms = [];
             for ($j = 0; $j < 14; $j++) {
                 array_push($terms, $cluster[$j]);
             }
             $all_users[] = ['cluster_id' => $i, 'cluster_terms' => $terms, 'num_of_users' => count($cluster)];
         }
         $statusCode = 200;
         $response = $all_users;
         return $response;
     } catch (Exception $e) {
         $statusCode = 400;
     } finally {
         return Response::json($response, $statusCode);
     }
 }
コード例 #8
0
 public function explicitrf_function(SignalsRequest $request)
 {
     $username = $request->username;
     $device = $request->device_id;
     $video_id = $request->video_id;
     $action_type = $request->action;
     $explicit_rf = $request->value;
     //check if $request->score==-1 or 0 or 1
     $record_exists = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_type)->first();
     if (empty($record_exists)) {
         $user_action = new UserAction(['username' => $username, 'device_id' => $device, 'video_id' => $video_id, 'explicit_rf' => $explicit_rf, 'action' => $action_type]);
         $user_action->save();
         $get_importance = Action::where('id', $request->action)->first();
         $importance = $get_importance->importance;
         $user_action->update(array('weight' => $explicit_rf, 'importance' => $importance));
     } else {
         $record_exists->update(array('explicit_rf' => $explicit_rf, 'weight' => $explicit_rf));
     }
     //store in the dcgs table - only used for the online experiments
     $mecanex_user = MecanexUser::where('username', $username)->first();
     $dcg_record = Dcg::where('mecanex_user_id', $mecanex_user->id)->where('video_id', $video_id);
     $dcg_record->update(array('explicit_rf' => $explicit_rf));
     //////////////calculate ku///////////////////////
     // number of all enrichments
     $video = Video::where('video_id', $video_id)->first();
     $num_all_enrichments = DB::select(DB::raw('SELECT COUNT(*) as num FROM enrichments_videos_time WHERE video_id=?'), [$video->id]);
     $num_all_enrichments = $num_all_enrichments[0]->num;
     // create list with clicked enrichments
     $get_action_id = Action::where('action', 'click enrichment')->first();
     $action_id = $get_action_id->id;
     $enrichment_click_ids = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->get(array('content_id'));
     $num_clicked_enrichments = count($enrichment_click_ids);
     // replace all database entries with one with the appropriate weight (so that the calculation can be easily done).
     // The information for what enrichments where clicked is now in the $enrichment_click_ids variable
     if ($num_clicked_enrichments != 0) {
         DB::table('user_actions')->where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->delete();
         $user_action = new UserAction(['username' => $username, 'device_id' => $device, 'video_id' => $video_id, 'action' => $action_id, 'content_id' => '1']);
         $user_action->save();
         $get_importance = Action::where('id', $action_id)->first();
         $importance = $get_importance->importance;
         $user_action->update(array('weight' => $num_clicked_enrichments / $num_all_enrichments, 'importance' => $importance));
     }
     // create list with shared enrichments
     $get_action_id = Action::where('action', 'share')->first();
     $action_id = $get_action_id->id;
     $enrichment_share_ids = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->get(array('content_id'));
     $num_shared_enrichments = count($enrichment_share_ids);
     // replace all database entries with one with the appropriate weight (so that the calculation can be easily done).
     // The information for what enrichments where clicked is now in the $enrichment_shared_ids variable
     if ($num_shared_enrichments != 0) {
         DB::table('user_actions')->where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->delete();
         $user_action = new UserAction(['username' => $username, 'device_id' => $device, 'video_id' => $video_id, 'action' => $action_id, 'content_id' => '1']);
         $user_action->save();
         $get_importance = Action::where('id', $action_id)->first();
         $importance = $get_importance->importance;
         $user_action->update(array('weight' => $num_shared_enrichments / $num_all_enrichments, 'importance' => $importance));
     }
     $k_nominator = UserAction::where('username', $username)->where('video_id', $video_id)->groupBy('username')->get(['username', DB::raw('SUM(importance*weight) as total_score')])->first();
     $query = "SELECT SUM(t1.importance ) AS total FROM (SELECT DISTINCT action, importance FROM user_actions WHERE username=:username AND video_id=:videoid) AS t1 ";
     $k_denominator = DB::select(DB::raw($query), array('username' => $username, 'videoid' => $video_id));
     //returns array
     $k = $k_nominator->total_score / $k_denominator[0]->total;
     //to [0] gia na prospelasei to 1o stoixeio tou array pou einai to object
     /////////////////////////////update weights and update profile//////////////////////////////////////////////////////////
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     /////////////Retrieve Terms/////////////////////////////
     //////////////retrieve terms for given video//////////////
     $video = Video::where('video_id', $request->video_id)->first();
     $threshold = 0;
     //need to appropriate set
     $results = $video->term()->where('video_score', '>', $threshold)->get(array('term_id'));
     $video_term_list = [];
     foreach ($results as $result) {
         //retrieve the terms that will be updated
         array_push($video_term_list, $result->term_id);
     }
     sort($video_term_list);
     ///////////retrieve terms for the clicked enrichments//////////////
     //		$get_actionid = Action::where('action', 'click enrichment')->first();
     //		$action_id = $get_actionid->id;
     //		$enrichment_ids = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->get(array('content_id'));
     $enrichment_term_list = [];
     //		foreach ($enrichment_ids as $enrichment_id)
     //		{
     //
     //			//call the api and get some terms
     //			//or emulate enrichment_terms
     //			//$results=Enrichment::where('id',$enrichment_id)->get(array('term_id'))
     //			foreach($results as $result)
     //			{
     //				array_push($enrichment_term_list,$result->term_id);
     //			}
     //
     //		}
     //$enrichment_terms=array_unique($enrichment_term_list);
     $enrichment_terms = [3, 4, 7];
     //retrieve terms for the clicked ads
     $ads_terms = [4, 8, 10];
     ///Final term_list -  no need since I will update in three steps
     //		$term_list=array_merge($video_term_list,$enrichment_terms,$ads_terms);
     //		$terms=array_unique($term_list);
     ////////////////update weights of profile//////////////////////////
     $term_scores = [];
     //save all scores to get the max
     $user = MecanexUser::where('username', $username)->get()->first();
     $video = Video::where('video_id', $video_id)->get()->first();
     $link_user = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->get()->first();
     //return $video;
     //return $link_user;
     //update based on video_terms
     //return $video_term_list;
     foreach ($video_term_list as $video_term_id) {
         $temp_user = $user->term->find($video_term_id);
         $user_term_score = $temp_user->pivot->user_score;
         //get score of user
         $temp_video = $video->term->find($video_term_id);
         $video_term_score = $temp_video->pivot->video_score;
         //get score of video
         $final_score = $k * (0.8 * $video_term_score);
         foreach ($enrichment_click_ids as $enrichment_click_id) {
             $id = $enrichment_click_id->content_id;
             $enrichment = Enrichment::where('enrichment_id', $id)->get()->first();
             $temp_enrichment = $enrichment->term->find($video_term_id);
             $enrichment_term_score = $temp_enrichment->pivot->enrichment_score;
             $final_score = $final_score + $k * (0.1 / $num_clicked_enrichments * $enrichment_term_score);
         }
         foreach ($enrichment_share_ids as $enrichment_share_id) {
             $id = $enrichment_share_id->content_id;
             $enrichment = Enrichment::where('enrichment_id', $id)->get()->first();
             $temp_enrichment = $enrichment->term->find($video_term_id);
             $enrichment_term_score = $temp_enrichment->pivot->enrichment_score;
             $final_score = $final_score + $k * (0.1 / $num_shared_enrichments * $enrichment_term_score);
         }
         //update score
         $new_score = $user_term_score + $final_score;
         //ok
         $new_score = max($new_score, 0);
         // don't let negative values
         array_push($term_scores, $new_score);
         //				//store score
         $user->term()->sync([$video_term_id => ['user_score' => $new_score]], false);
     }
     //return $term_scores;
     // update matrix
     $number_video_terms = count($video_term_list);
     $link_term_scores = [];
     //save all scores to get the max
     for ($i = 0; $i <= $number_video_terms - 1; $i++) {
         for ($j = $i + 1; $j < $number_video_terms; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $video_term_list[$i])->where('term_neighbor_id', $video_term_list[$j])->get()->first();
             //return $temp_user_matrix;
             $temp_video = $video->term->find($video_term_list[$i]);
             $video_term_score1 = $temp_video->pivot->video_score;
             $temp_video = $video->term->find($video_term_list[$j]);
             $video_term_score2 = $temp_video->pivot->video_score;
             $final_score = $k * (0.8 * $video_term_score1 * $video_term_score2);
             foreach ($enrichment_click_ids as $enrichment_click_id) {
                 $id = $enrichment_click_id->content_id;
                 $enrichment = Enrichment::where('enrichment_id', $id)->get()->first();
                 $temp_enrichment = $enrichment->term->find($video_term_list[$i]);
                 $enrichment_term_score1 = $temp_enrichment->pivot->enrichment_score;
                 $temp_enrichment = $enrichment->term->find($video_term_list[$j]);
                 $enrichment_term_score2 = $temp_enrichment->pivot->enrichment_score;
                 $final_score = $final_score + $k * (0.1 / $num_clicked_enrichments * $enrichment_term_score1 * $enrichment_term_score2);
             }
             foreach ($enrichment_share_ids as $enrichment_share_id) {
                 $id = $enrichment_share_id->content_id;
                 $enrichment = Enrichment::where('enrichment_id', $id)->get()->first();
                 $temp_enrichment = $enrichment->term->find($video_term_list[$i]);
                 $enrichment_term_score1 = $temp_enrichment->pivot->enrichment_score;
                 $temp_enrichment = $enrichment->term->find($video_term_list[$j]);
                 $enrichment_term_score2 = $temp_enrichment->pivot->enrichment_score;
                 $final_score = $final_score + $k * (0.1 / $num_shared_enrichments * $enrichment_term_score1 * $enrichment_term_score2);
             }
             $new_score = $temp_user_matrix->link_score + $final_score;
             $new_score = max($new_score, 0);
             // don't let negative values
             array_push($link_term_scores, $new_score);
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     //same should be done for enrichments and ads
     //find max value and divide term values
     $max_term_value = max(max($term_scores), 1);
     if ($link_term_scores != []) {
         $max_link_term_value = max(max($link_term_scores), 1);
     }
     foreach ($video_term_list as $video_term_id) {
         $temp_user = $user->term->find($video_term_id);
         $user_term_score = $temp_user->pivot->user_score;
         //get score of user
         $temp_video = $video->term->find($video_term_id);
         $video_term_score = $temp_video->pivot->video_score;
         //get score of video
         //update score
         $new_score = $user_term_score / $max_term_value;
         //ok
         //store score
         $user->term()->sync([$video_term_id => ['user_score' => $new_score]], false);
     }
     for ($i = 0; $i <= $number_video_terms - 1; $i++) {
         for ($j = $i + 1; $j < $number_video_terms; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $video_term_list[$i])->where('term_neighbor_id', $video_term_list[$j])->get()->first();
             $old_score = $temp_user_matrix->link_score;
             $new_score = $old_score / $max_link_term_value;
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     //calculate profile
     $terms = Term::all()->count();
     for ($j = 1; $j <= $terms; $j++) {
         $profile_score = 0;
         for ($i = 1; $i <= $terms; $i++) {
             $temp_user = $user->term->find($i);
             $user_term_score = $temp_user->pivot->user_score;
             //get score of user
             if ($i == $j) {
                 $link_score = 0;
             } elseif ($i > $j) {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $j)->where('term_neighbor_id', $i)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             } else {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $i)->where('term_neighbor_id', $j)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             }
             $profile_score = $profile_score + $user_term_score * $link_score;
         }
         $user->profilescore()->sync([$j => ['profile_score' => $profile_score]], false);
     }
     DB::table('user_actions')->where('username', $username)->where('video_id', $video_id)->delete();
     $response = ["message" => 'RF Saved'];
     $statusCode = 200;
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #9
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function login(Request $request, SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
 {
     //test if token for FB login is enough
     $token = $request->token;
     //			return $token;
     // does not work since $token is string but should be token
     //		if (! $token->isLongLived()) {
     //			// OAuth 2.0 client handler
     //			$oauth_client = $fb->getOAuth2Client();
     //
     //			// Extend the access token.
     //			try {
     //				$token = $oauth_client->getLongLivedAccessToken($token);
     //			} catch (Facebook\Exceptions\FacebookSDKException $e) {
     //				dd($e->getMessage());
     //			}
     //		}
     //this is for not include $token in the get calls
     $fb->setDefaultAccessToken($token);
     // Get basic info on the user from Facebook.
     try {
         $response = $fb->get('/me?fields=id,email');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     try {
         $profileresponse = $fb->get('/me?fields=id,name,gender');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     // Convert the response to a `Facebook/GraphNodes/GraphUser` collection
     $facebook_user = $response->getGraphUser();
     $mecanex_user = $profileresponse->getGraphUser();
     $existing_mecanex_user = MecanexUser::where('email', '=', $facebook_user["email"])->get()->first();
     $existing_user = User::where('email', '=', $facebook_user["email"])->get()->first();
     // Create the user if it does not exist or update the existing entry.
     // This will only work if you've added the SyncableGraphNodeTrait to your User model.
     if ($existing_user == null) {
         $facebook_user["username"] = "******" . $facebook_user["id"];
         $user = User::createOrUpdateGraphNode($facebook_user);
     } else {
         $facebook_user["username"] = $existing_user->username;
         $user = $existing_user;
         $user->facebook_user_id = $facebook_user["id"];
         $user->save();
     }
     //store profile data in mecanex_users table
     $id = $user->id;
     $facebook_id = $user->facebook_user_id;
     if ($existing_mecanex_user == null) {
         $username = "******" . $user->facebook_user_id;
     } else {
         $username = $existing_mecanex_user->username;
     }
     $email = $user->email;
     $fullname = $mecanex_user->getName();
     $fullname = explode(" ", $fullname);
     $name = $fullname[0];
     $surname = $fullname[1];
     $gender = $mecanex_user->getGender();
     if ($gender == 'female') {
         $gender_id = 2;
     } else {
         $gender_id = 1;
     }
     $fbuser = MecanexUser::firstOrNew(array('email' => $email));
     $fbuser->username = $username;
     $fbuser->user_id = $id;
     $fbuser->facebook_user_id = $facebook_id;
     $fbuser->gender_id = $gender_id;
     $fbuser->name = $name;
     $fbuser->surname = $surname;
     $fbuser->email = $email;
     $fbuser->save();
     // Log the user into Laravel
     Auth::login($user);
     // create records in table users_terms-scores once a mecanex user has been created
     if ($existing_mecanex_user == null) {
         $terms = Term::all();
         $total_terms = count($terms);
         foreach ($terms as $term) {
             $fbuser->term()->sync([$term->id => ['user_score' => 0]], false);
             $fbuser->profilescore()->sync([$term->id => ['profile_score' => 0]], false);
         }
         for ($i = 1; $i <= $total_terms; $i++) {
             for ($j = $i + 1; $j <= $total_terms; $j++) {
                 $mec_matrix = new MecanexUserTermHomeTermNeighbour();
                 $mec_matrix->mecanex_user_id = $fbuser->id;
                 $mec_matrix->term_home_id = $i;
                 $mec_matrix->term_neighbor_id = $j;
                 $mec_matrix->link_score = 0.05;
                 $mec_matrix->save();
             }
         }
     }
     $response = ['username' => $username, 'message' => 'User was successfully logged in'];
     $statusCode = 201;
     return response($response, $statusCode)->header('Content-Type', 'application/json');
 }
コード例 #10
0
 public function callback(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
 {
     //		$token = $fb->getAccessTokenFromRedirect();
     //		dd($token);
     // Obtain an access token.
     try {
         $token = $fb->getAccessTokenFromRedirect();
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     // Access token will be null if the user denied the request
     // or if someone just hit this URL outside of the OAuth flow.
     if (!$token) {
         // Get the redirect helper
         $helper = $fb->getRedirectLoginHelper();
         if (!$helper->getError()) {
             abort(403, 'Unauthorized action.');
         }
         // User denied the request
         //				echo '<p>Error: ' . $helper->getError();
         //				echo '<p>Code: ' . $helper->getErrorCode();
         //				echo '<p>Reason: ' . $helper->getErrorReason();
         //				echo '<p>Description: ' . $helper->getErrorDescription();
         //				exit ;
         dd($helper->getError(), $helper->getErrorCode(), $helper->getErrorReason(), $helper->getErrorDescription());
     }
     $fb->setDefaultAccessToken($token);
     if (!$token->isLongLived()) {
         // OAuth 2.0 client handler
         $oauth_client = $fb->getOAuth2Client();
         // Extend the access token.
         try {
             $token = $oauth_client->getLongLivedAccessToken($token);
         } catch (Facebook\Exceptions\FacebookSDKException $e) {
             dd($e->getMessage());
         }
     }
     //this is for not include $token in the get calls
     $fb->setDefaultAccessToken($token);
     // Get basic info on the user from Facebook.
     try {
         $response = $fb->get('/me?fields=id,email');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     try {
         $profileresponse = $fb->get('/me?fields=id,name,gender');
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         dd($e->getMessage());
     }
     // Convert the response to a `Facebook/GraphNodes/GraphUser` collection
     $facebook_user = $response->getGraphUser();
     $mecanex_user = $profileresponse->getGraphUser();
     $existing_mecanex_user = MecanexUser::where('facebook_user_id', '=', $facebook_user["id"])->get()->first();
     $existing_user = User::where('facebook_user_id', '=', $facebook_user["id"])->get()->first();
     // Create the user if it does not exist or update the existing entry.
     // This will only work if you've added the SyncableGraphNodeTrait to your User model.
     if ($existing_user == null) {
         $facebook_user["username"] = "******" . $facebook_user["id"];
     } else {
         $facebook_user["username"] = $existing_user->username;
     }
     $user = User::createOrUpdateGraphNode($facebook_user);
     //store profile data in mecanex_users table
     $id = $user->id;
     $facebook_id = $user->facebook_user_id;
     if ($existing_mecanex_user == null) {
         $username = "******" . $user->facebook_user_id;
     } else {
         $username = $existing_mecanex_user->username;
     }
     $email = $user->email;
     $fullname = $mecanex_user->getName();
     $fullname = explode(" ", $fullname);
     $name = $fullname[0];
     $surname = $fullname[1];
     $gender = $mecanex_user->getGender();
     if ($gender == 'female') {
         $gender_id = 2;
     } else {
         $gender_id = 1;
     }
     $fbuser = MecanexUser::firstOrNew(array('facebook_user_id' => $facebook_id));
     $fbuser->username = $username;
     $fbuser->user_id = $id;
     $fbuser->facebook_user_id = $facebook_id;
     $fbuser->gender_id = $gender_id;
     $fbuser->name = $name;
     $fbuser->surname = $surname;
     $fbuser->email = $email;
     $fbuser->save();
     // Log the user into Laravel
     Auth::login($user);
     if ($existing_mecanex_user == null) {
         // create records in table users_terms-scores once a mecanex user has been created
         $terms = Term::all();
         $total_terms = count($terms);
         foreach ($terms as $term) {
             $fbuser->term()->sync([$term->id => ['user_score' => 0]], false);
             $fbuser->profilescore()->sync([$term->id => ['profile_score' => 0]], false);
         }
         for ($i = 1; $i <= $total_terms; $i++) {
             for ($j = $i + 1; $j <= $total_terms; $j++) {
                 $mec_matrix = new MecanexUserTermHomeTermNeighbour();
                 $mec_matrix->mecanex_user_id = $fbuser->id;
                 $mec_matrix->term_home_id = $i;
                 $mec_matrix->term_neighbor_id = $j;
                 $mec_matrix->link_score = 0.05;
                 $mec_matrix->save();
             }
         }
     }
     return redirect('/home')->with('message', 'Successfully logged in with Facebook');
 }
コード例 #11
0
 private function content_similarity($user_id, $video_ids)
 {
     $temp_profile_scores = [];
     // if there is no video list, search all videos, else only those on the list
     if (count($video_ids) == 0) {
         $videos = Video::all();
     } else {
         //            $videos = Video::whereRaw('video_id  IN (' . $video_ids . ')')->get();
         $tmpArray = explode(',', $video_ids);
         $func = function ($string) {
             return substr($string, 1, -1);
         };
         $myArray = array_map($func, $tmpArray);
         $videos = DB::table('videos')->whereIn('video_id', $myArray)->get();
     }
     //keep all terms of the user in a list
     $terms = Term::all();
     $user = MecanexUser::where('id', $user_id)->get()->first();
     $user_terms_scores = $user->profilescore;
     foreach ($user_terms_scores as $user_term_score) {
         $temp_profile_scores[] = $user_term_score->pivot->profile_score;
     }
     foreach ($videos as $video) {
         $arithmitis = 0;
         $sumA = 0;
         $sumB = 0;
         $temp_video_scores = [];
         //keep all terms of video in a list
         $video_terms_scores = DB::select(DB::raw('SELECT * FROM videos_terms_scores WHERE video_id=? ORDER BY term_id'), [$video->id]);
         foreach ($video_terms_scores as $video_term_score) {
             $temp_video_scores[] = $video_term_score->video_score;
         }
         // calculate the similarity
         for ($i = 0; $i < count($terms); $i++) {
             $arithmitis = $arithmitis + $temp_video_scores[$i] * $temp_profile_scores[$i];
             $sumA = $sumA + pow($temp_video_scores[$i], 2);
             $sumB = $sumB + pow($temp_profile_scores[$i], 2);
         }
         $videoScores[$video->id] = $arithmitis / (sqrt($sumA) + sqrt($sumB));
     }
     return $videoScores;
 }
コード例 #12
0
 private function content_similarity($user_id, $limit)
 {
     $result = [];
     $videos = Video::all();
     $terms = Term::all();
     $user = MecanexUser::where('id', $user_id)->get()->first();
     $user_terms_scores = $user->profilescore;
     foreach ($user_terms_scores as $user_term_score) {
         $temp_profile_scores[] = $user_term_score->pivot->profile_score;
     }
     foreach ($videos as $video) {
         $arithmitis = 0;
         $sumA = 0;
         $sumB = 0;
         $temp_video_scores = [];
         $video_terms_scores = DB::select(DB::raw('SELECT * FROM videos_terms_scores WHERE video_id=? ORDER BY term_id'), [$video->id]);
         foreach ($video_terms_scores as $video_term_score) {
             $temp_video_scores[] = $video_term_score->video_score;
         }
         for ($i = 0; $i < count($terms); $i++) {
             $arithmitis = $arithmitis + $temp_video_scores[$i] * $temp_profile_scores[$i];
             $sumA = $sumA + pow($temp_video_scores[$i], 2);
             $sumB = $sumB + pow($temp_profile_scores[$i], 2);
         }
         $videoScores[$video->id] = $arithmitis / (sqrt($sumA) + sqrt($sumB));
     }
     arsort($videoScores);
     $videoScores = array_slice($videoScores, 0, $limit, true);
     foreach ($videoScores as $key => $score) {
         $video = $videos->find($key);
         $result[] = array('video_id' => $video->id, 'title' => $video->title, 'similarity' => $score, 'euscreen_id' => $video->video_id);
     }
     return $result;
 }
コード例 #13
0
 /**
  * Return clusterheads and corresponding videos for filtered users.
  *
  * @return Clusterheads and videos
  */
 public function professional(Request $request)
 {
     try {
         $mecanexusers = MecanexUser::all();
         // filter by demographics
         if ($request->gender_id != 0) {
             $mecanexusers = $mecanexusers->where("gender_id", (int) $request->gender_id);
         }
         if ($request->age_id != 0) {
             $mecanexusers = $mecanexusers->where("age_id", (int) $request->age_id);
         }
         if ($request->education_id != 0) {
             $mecanexusers = $mecanexusers->where("education_id", (int) $request->education_id);
         }
         if ($request->occupation_id != 0) {
             $mecanexusers = $mecanexusers->where("occupation_id", (int) $request->occupation_id);
         }
         if ($request->country_id != 0) {
             $mecanexusers = $mecanexusers->where("country_id", (int) $request->country_id);
         }
         if ($request->num != 0) {
             $num = $request->num;
         } else {
             $num = 50;
         }
         // filter by preference on terms
         // keep mecanex users whose term profile score is more than 0.7 when normalized by the max term value of the user
         if ($request->terms != []) {
             $all_terms = Term::all();
             foreach ($all_terms as $term) {
                 if (strpos($request->terms, $term->term) !== false) {
                     $mecanexusers = $mecanexusers->filter(function ($user) use($term) {
                         $myquery = DB::select(DB::raw(' SELECT MAX(profile_score) as mymax
                                                        FROM users_terms_profilescores
                                                        WHERE mecanex_user_id=' . $user->id . ''));
                         if ($myquery[0]->mymax == 0) {
                             // don't take into account users that have not provided any information
                             return false;
                         }
                         return $user->profilescore[$term->id - 1]['pivot']['profile_score'] / $myquery[0]->mymax > 0.7;
                         // minus one because terms start from 0 where id starts from 1
                     });
                     //                        $response[] = $mecanexusers[1]->profilescore[$term->id-1]['pivot']['profile_score'];
                     //                        $myquery = DB::select(DB::raw(' SELECT MAX(profile_score) as mymax
                     //                                                           FROM users_terms_profilescores
                     //                                                           WHERE mecanex_user_id='. $mecanexusers[2]->id .''));
                 }
             }
         }
         $array_of_users = array();
         // If no mecanexusers exist from the filters selected, we return a random list of videos
         if ($mecanexusers->isEmpty()) {
             if ($request->videos == null) {
                 $videos = Video::orderByRaw('RAND()')->take($num)->get();
             } else {
                 $reqvideos = "'" . str_replace(",", "','", $request->videos) . "'";
                 //                    $videos = Video::where('video_id','in',['EUS_025A722EA4B240D8B6F6330A8783143C'])->orderByRaw('RAND()')->take($num)->get();
                 $videos = DB::select(DB::raw(' SELECT *
                                         FROM videos
                                         WHERE video_id IN (' . $reqvideos . ') ORDER BY RAND()  LIMIT ' . $num . ''));
             }
             $response = [];
             foreach ($videos as $video) {
                 $response['videos'][] = $video->video_id;
             }
             $statusCode = 200;
             return $response;
         }
         foreach ($mecanexusers as $mecanexuser) {
             $array = array();
             $terms = $mecanexuser->profilescore;
             foreach ($terms as $term) {
                 $temp = (double) $term['pivot']['profile_score'];
                 array_push($array, $temp);
             }
             array_push($array_of_users, $array);
         }
         /** return the array of users so that we can see whether the profiles have normalized
          * values so that they can be clustered properly
          */
         //            return $array_of_users;
         $space = new Space(14);
         $num_of_clusters = 5;
         foreach ($array_of_users as $point) {
             $space->addPoint($point);
         }
         $clusters = $space->solve($num_of_clusters);
         $statusCode = 200;
         $all_users = [];
         //            foreach ($clusters as $i => $cluster)
         //                printf("Cluster %d [%d,%d]: %d points\n", $i, $cluster[0], $cluster[1], count($cluster));
         foreach ($clusters as $i => $cluster) {
             $terms = [];
             for ($j = 0; $j < 14; $j++) {
                 array_push($terms, $cluster[$j]);
             }
             $all_users[] = ['cluster_id' => $i, 'cluster_terms' => $terms, 'num_of_users' => count($cluster)];
         }
         $cluster_list = [];
         foreach ($all_users as $user) {
             $cluster_list[] = ['cluster_id' => $user['cluster_id'], 'video_ids' => $this->recommend_video($user['cluster_terms'], $request), 'cluster_terms' => $user['cluster_terms'], 'num_of_users' => $user['num_of_users']];
         }
         //            $response = $cluster_list[0]['video_ids'][0]->id;
         $video_list = [];
         $response = [];
         $num_of_videos = 0;
         $total_num_of_videos = count($cluster_list[0]['video_ids']);
         for ($i = 0; $i < $total_num_of_videos; $i++) {
             for ($j = 0; $j < $num_of_clusters; $j++) {
                 $video = $cluster_list[$j]['video_ids'][$i];
                 if (!in_array($video->video_id, $video_list, true)) {
                     $video_list[] = $video->video_id;
                     $response['videos'][] = $video->euscreen_id;
                     $num_of_videos += 1;
                 }
                 if ($num_of_videos == $total_num_of_videos) {
                     break;
                 }
             }
             if ($num_of_videos == $total_num_of_videos) {
                 break;
             }
         }
         return $response;
     } catch (Exception $e) {
         $statusCode = 400;
     } finally {
         return Response::json($response, $statusCode);
     }
 }
コード例 #14
0
ファイル: VideoController.php プロジェクト: skafetzo/SPtool
 public function rf(Request $request)
 {
     $user = Auth::user();
     $username = $user->username;
     $device = "1";
     $video_id = $request->video_id;
     $action_type = 6;
     $explicit_rf = $request->score;
     //check if $request->score==-1 or 0 or 1
     $record_exists = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_type)->first();
     if (empty($record_exists)) {
         $user_action = new UserAction(['username' => $username, 'device_id' => '1', 'video_id' => $video_id, 'explicit_rf' => $explicit_rf, 'action' => $action_type]);
         $user_action->save();
         $get_importance = Action::where('id', $action_type)->first();
         $importance = $get_importance->importance;
         $user_action->update(array('weight' => 1, 'importance' => $importance));
         return $record_exists;
     } else {
         $record_exists->update(array('explicit_rf' => $explicit_rf));
     }
     //store in the dcgs table - only used for the online experiments
     $mecanex_user = MecanexUser::where('username', $username)->first();
     $dcg_record = Dcg::where('mecanex_user_id', $mecanex_user->id)->where('video_id', $video_id);
     $dcg_record->update(array('explicit_rf' => $explicit_rf));
     //////////////calculate ku///////////////////////
     $k_nominator = UserAction::where('username', $username)->where('video_id', $video_id)->groupBy('username')->get(['username', DB::raw('SUM(importance*weight) as total_score')])->first();
     //prepei edw na to diairw k me to plithos twn sunolikwn enrichments k ads
     $query = "SELECT SUM(t1.importance ) AS total FROM (SELECT DISTINCT action, importance FROM user_actions WHERE username=:username AND video_id=:videoid) AS t1 ";
     $k_denominator = DB::select(DB::raw($query), array('username' => $username, 'videoid' => $video_id));
     //returns array
     $k = $k_nominator->total_score / $k_denominator[0]->total;
     //to [0] gia na prospelasei to 1o stoixeio tou array pou einai to object
     /////////////////////////////update weights and update profile//////////////////////////////////////////////////////////
     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     /////////////Retrieve Terms/////////////////////////////
     //////////////retrieve terms for given video//////////////
     $video = Video::where('video_id', $video_id)->first();
     $threshold = 0.1;
     //need to appropriate set
     $results = $video->term()->where('video_score', '>', $threshold)->distinct()->get(array('term_id'));
     //$results = $results->unique();
     //return $results;
     $video_term_list = [];
     foreach ($results as $result) {
         //retrieve the terms that will be updated
         array_push($video_term_list, $result->term_id);
     }
     sort($video_term_list);
     //return $video_term_list;
     ///////////retrieve terms for the clicked enrichments//////////////
     $get_actionid = Action::where('action', 'click enrichment')->first();
     $action_id = $get_actionid->id;
     $enrichment_ids = UserAction::where('username', $username)->where('video_id', $video_id)->where('action', $action_id)->get(array('content_id'));
     $enrichment_term_list = [];
     //		foreach ($enrichment_ids as $enrichment_id)
     //		{
     //
     //			//call the api and get some terms
     //			//or emulate enrichment_terms
     //			//$results=Enrichment::where('id',$enrichment_id)->get(array('term_id'))
     //			foreach($results as $result)
     //			{
     //				array_push($enrichment_term_list,$result->term_id);
     //			}
     //
     //		}
     //$enrichment_terms=array_unique($enrichment_term_list);
     //		$enrichment_terms = [3, 4, 7];
     //retrieve terms for the clicked ads
     //		$ads_terms = [4, 8, 10];
     ///Final term_list -  no need since I will update in three steps
     //		$term_list=array_merge($video_term_list,$enrichment_terms,$ads_terms);
     //		$terms=array_unique($term_list);
     ////////////////update weights of profile//////////////////////////
     $term_scores = [];
     //save all scores to get the max
     $user = MecanexUser::where('username', $username)->get()->first();
     $video = Video::where('video_id', $video_id)->get()->first();
     $link_user = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->get()->first();
     //return $link_user;
     //update based on video_terms
     foreach ($video_term_list as $video_term_id) {
         $temp_user = $user->term->find($video_term_id);
         $user_term_score = $temp_user->pivot->user_score;
         //get score of user
         $temp_video = $video->term->find($video_term_id);
         $video_term_score = $temp_video->pivot->video_score;
         //get score of video
         //update score
         $new_score = $user_term_score + $k * (0.8 * $video_term_score);
         //ok
         array_push($term_scores, $new_score);
         //				//store score
         $user->term()->sync([$video_term_id => ['user_score' => $new_score]], false);
     }
     // update matrix
     $number_video_terms = count($video_term_list);
     $link_term_scores = [];
     //save all scores to get the max
     for ($i = 0; $i <= $number_video_terms - 1; $i++) {
         for ($j = $i + 1; $j < $number_video_terms; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $video_term_list[$i])->where('term_neighbor_id', $video_term_list[$j])->get()->first();
             //return $temp_user_matrix;
             $temp_video = $video->term->find($video_term_list[$i]);
             $video_term_score1 = $temp_video->pivot->video_score;
             $temp_video = $video->term->find($video_term_list[$j]);
             $video_term_score2 = $temp_video->pivot->video_score;
             //return $temp_user_matrix;
             $new_score = $temp_user_matrix->link_score + $k * (0.8 * ($video_term_score1 * $video_term_score2));
             array_push($link_term_scores, $new_score);
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     //same should be done for enrichments and ads
     //find max value and divide term values
     $max_term_value = max($term_scores);
     $max_link_term_value = max($link_term_scores);
     foreach ($video_term_list as $video_term_id) {
         $temp_user = $user->term->find($video_term_id);
         $user_term_score = $temp_user->pivot->user_score;
         //get score of user
         $temp_video = $video->term->find($video_term_id);
         $video_term_score = $temp_video->pivot->video_score;
         //get score of video
         //update score
         $new_score = $user_term_score / $max_term_value;
         //ok
         //				//store score
         $user->term()->sync([$video_term_id => ['user_score' => $new_score]], false);
     }
     for ($i = 0; $i <= $number_video_terms - 1; $i++) {
         for ($j = $i + 1; $j < $number_video_terms; $j++) {
             $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $video_term_list[$i])->where('term_neighbor_id', $video_term_list[$j])->get()->first();
             $old_score = $temp_user_matrix->link_score;
             $new_score = $old_score / $max_link_term_value;
             $temp_user_matrix->link_score = $new_score;
             $temp_user_matrix->save();
         }
     }
     //calculate profile
     $terms = Term::all()->count();
     for ($j = 1; $j <= $terms; $j++) {
         $profile_score = 0;
         for ($i = 1; $i <= $terms; $i++) {
             $temp_user = $user->term->find($i);
             $user_term_score = $temp_user->pivot->user_score;
             //get score of user
             if ($i == $j) {
                 $link_score = 0;
             } elseif ($i > $j) {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $j)->where('term_neighbor_id', $i)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             } else {
                 $temp_user_matrix = MecanexUserTermHomeTermNeighbour::where('mecanex_user_id', $user->id)->where('term_home_id', $i)->where('term_neighbor_id', $j)->get()->first();
                 $link_score = $temp_user_matrix->link_score;
             }
             $profile_score = $profile_score + $user_term_score * $link_score;
         }
         $user->profilescore()->sync([$j => ['profile_score' => $profile_score]], false);
     }
     //	DB::table('user_actions')->where('username',$username)->where('video_id', $video_id)->delete();
     return Redirect::route('home')->with('message', 'Thank you for watching the video');
 }