Detecting the mood of a tweet or message - php

Are there any APIs that can extract moods from a string (for use in PHP but can be implemented in any language)?
If one doesn't exist, how would I go about building a classifier, presumably something related to machine learning, where I extract words with known positive/negativity.

I would suggest AlchemyAPI. They have pretty simple APIs ( which shouldn't be difficult to use. For your specific case, look into here

Using the above suggestion of AlchemyapI, here is a really simple system based on Facebook statuses'
$id = CURRENT USER ID;
$message = array(); //the users posts with scores
$status = $fb->fql("SELECT status_id, message FROM status WHERE uid=$id LIMIT 10");
foreach($status as $stat) {
$message = file_get_contents("http://access.alchemyapi.com/calls/text/TextGetTextSentiment"
."?outputMode=json&apikey=MYAPIKEY"
."&text=".urlencode($stat['message']));
$data = json_decode($message); //get reply
$messages[] = array("status"=>$stat['message'], "score"=>($data->docSentiment->type!="neutral") ? $data->docSentiment->score : 0); //save reply
}
$user = $fb->api("/".$id); //query the user
$content .= "<h3>".$user['name']."</h3>";
$total = 0;
$count = 0;
foreach($messages as $message) {
$total += $message['score'];
if($message['score']!=0) $count++;
}
$content .= 'Has an average rating of '.$total/$count.' <meter min="-1" max="1" value="'.$total/$count.'"></meter><br /><br />';
foreach($messages as $message) {
$content .= '<b>'.$message['status'].'</b> '.$message['score'].'</br>'
.'<meter ' //class="'.($message['score'] == 0 ? "yellow" : $message['score'] < 0 ? "red" : "green").'" '
.'value="'.$message['score'].'" min="-0.5" max="0.5" optimum="0">'.$message['score'].' out of -1 to 1</meter><br /><br />';
}

Related

HTML - String containing color codes to color

I'm currently facing a problem here, I have many different strings like these:
"he#00ff00llo"
"#cc9200test"
And so on.
I'm outputting this on an HTML page (Grabbing it through my database)
Anyways, what I want to achieve is to read those #00ff00 and output it as the color itself.
EDIT:
these are usernames, and most of the time they go like this: #ff0000#SomeName | Which I then want to turn into <span style="color: #ff0000">#SomeName</span> oh and the there are usernames with several colorcodes.
EDIT:
My friend gave me this code which solved my problem. :)
IT WAS SOLVED IN PHP
ALSO THE CODE BELOW (Posted by Oriol) IS WORKING! :)
THIS CODE WORKS(PHP):
<?php
function colorCodesRenderProperly($name)
{
$name = htmlspecialchars($name);
if(preg_match('/^(#[0-9a-fA-F]{6})+$/', $name) === 1)
{
return $name;
}
preg_match_all('/#[0-9a-fA-F]{6}/', $name, $codes);
$replaced = array();
$codes_original = $codes;
$i = 0;
$count = 1;
foreach($codes[0] as &$code)
{
if(in_array($codes_original[0][$i], $replaced))
{
continue;
}
$code = sprintf('%02s', dechex((hexdec($code[1].$code[2])/255*128)))
.sprintf('%02s', dechex((hexdec($code[3].$code[4])/255*128)))
.sprintf('%02s', dechex((hexdec($code[5].$code[6])/255*128)));
$name = str_replace($codes_original[0][$i], "<span style=\"color: #$code;\">", $name, $count);
$replaced[] = $codes_original[0][$i];
$i++;
$count = 1;
}
while($i > 0)
{
$name .= "</span>";
$i--;
}
return $name;
}
?>
Try this:
var txt = document.createTextNode("he#00ff00llo"),
wrapper = document.createElement('span'),
regExp = /#[\da-f]{6}/i,
pos;
wrapper.appendChild(txt);
while(~(pos = txt.nodeValue.search(regExp))) {
txt = txt.splitText(pos);
var span = wrapper.cloneNode(false);
span.style.color = txt.nodeValue.substr(0,7);
txt.nodeValue = txt.nodeValue.substr(7);
span.appendChild(txt);
wrapper.appendChild(span);
}
// append wrapper to the DOM

PHP Search Script Enhancement

I have a website that has a built in search function. It allows the users to search for keywords from within the main page header. When a user searches any keyword, the result is always:
There are no results matching your query.
In order to find any item, the user must go to the advanced search options and enter the keyword in the search box, select the checkbox for "Search item title and description" and select "Both" from the drop down box for "Listed In".
I cannot figure out how to automatically set the main page search box to search each of these options.
Below is the code that I have for the search function. Any help would be GREATLY APPRECIATED:
<?php
session_start();
define ('IN_SITE', 1);
include_once ('includes/global.php');
include_once ('includes/class_formchecker.php');
include_once ('includes/class_custom_field.php');
include_once ('global_header.php');
$option = $db->rem_special_chars($_REQUEST['option']);
$option = (empty($option)) ? 'auction_search' : $option;
$template->set('option', $option);
$item_details = $db->rem_special_chars_array($_POST);
$template->set('item_details', $item_details);
$header_search_page = header5(GMSG_ADVANCED_SEARCH);
$template->set('header_search_page', $header_search_page);
if ($_REQUEST['search_empty'] == 1)
{
$template->set('no_results_message', '<p align="center" class="errormessage">' . MSG_NO_RESULTS_QUERY . '</p>');
}
(string) $search_options_menu = null;
$search_options_menu .= display_link(process_link('search', array('option' => 'auction_search')), MSG_AUCTION_SEARCH, (($option = 'auction_search') ? false : true)) . ' | ';
$search_options_menu .= display_link(process_link('search', array('option' => 'seller_search')), MSG_SELLER_SEARCH, (($option = 'seller_search') ? false : true)) . ' | ';
$search_options_menu .= display_link(process_link('search', array('option' => 'buyer_search')), MSG_BUYER_SEARCH, (($option = 'buyer_search') ? false : true));
if ($setts['enable_stores'])
$template->set('search_options_menu', $search_options_menu);
switch ($option)
{
case 'auction_search':
$search_options_title = MSG_AUCTION_SEARCH;
$custom_fld = new custom_field();
$custom_fld->new_table = false;
$custom_fld->field_colspan = 2;
$custom_fld->box_search = 1;
$custom_sections_table = $custom_fld->display_sections($item_details, 'auction', false, 1, 0);
$template->set('custom_sections_table', $custom_sections_table);
$tax = new tax();
$template->set('country_dropdown', $tax->countries_dropdown('country', $item_details['country'], null, '', true));
//$template->set('state_box', $tax->states_box('state', $item_details['state'], $item_details['country']));
break;
case 'seller_search':
$search_options_title = MSG_SELLER_SEARCH;
break;
case 'buyer_search':
$search_options_title = MSG_BUYER_SEARCH;
break;
case 'store_search':
$search_options_title = MSG_STORE_SEARCH;
break;
}
$template->set('search_options_title', $search_options_title);
$template_output .= $template->process('search.tpl.php');
include_once ('global_footer.php');
echo $template_output;
?>
This issue after doing research was the result in a standard setting for MySQL. Minimum search length had to be longer than 3 characters. A search length of 3 characters or less yielded no search results.

PHP- Google Api getting goal completed amount

Im using this code from google api
I am getting all of the goals names and number
But I cant see a way to get the goal completed amount
This is what I get:
Account ID = xxx
Web Property ID = xxx
Internal Web Property ID = xxx
Profile ID = xxx
Goal Number = 1
Goal Name = Open User (MT Register)
Goal Value = 0
Goal Active = 1
Goal Type = URL_DESTINATION
Created = 2012-07-22T10:20:02.183Z
Updated = 2012-08-15T12:43:06.045Z
Goal URL = /04_thankyou.php
Case Sensitive =
Match Type = REGEX
First Step Required = 1
Destination Goal Steps
Step Number = 1
Step Name = abc
Step URL = /01_insert_phone.php
Step Number = 2
Step Name = abcd
Step URL = /02_progress.step
Step Number = 3
Step Name = abcde
Step URL = /03_insert_pincode.php
This is the code:
function getEventDetailsHtml(&$details) {
$html = '<h4>Event Goal</h4><pre>' .
'Use Event Value = ' . $details->getUseEventValue();
// Get all the event goal conditions.
$conditions = $details->getEventConditions();
foreach ($conditions as &$condition) {
$html .= "Event Type = $condition->getEventType()";
$eventType = $condition->getType();
if ($condition->getType() == 'VALUE') {
// Process VALUE.
$html .= "Comparison Type = $condition->getComparisonType()" .
"Comparison Value = $condition->getComparisonValue()";
} else {
// Process CATEGORY, ACTION, LABEL.
$html .= "Match Type = $condition->getMatchType()" .
"Expression = $condition->getExpression()";
}
}
return $html . '</pre>';
}
function getVisitNumPagesDetailsHtml(&$details) {
$html = '<h4>Visit Num Pages Goal</h4>';
$html .= <<<HTML
<pre>
Comparison Type = {$details->getComparisonType()}
Comparison Value = {$details->getComparisonValue()}
</pre>
HTML;
return $html;
}
function getVisitTimeOnSiteDetailsHtml(&$details) {
$html = '<h4>Visit Time On Site Goal</h4>';
$html .= <<<HTML
<pre>
Comparison Type = {$details->getComparisonType()}
Comparison Value = {$details->getComparisonValue()}
</pre>
HTML;
return $html;
}
function getUrlDestinationDetailsHtml(&$details) {
$html .= <<<HTML
<pre>
Goal URL = {$details->getUrl()}
Case Sensitive = {$details->getCaseSensitive()}
Match Type = {$details->getMatchType()}
First Step Required = {$details->getFirstStepRequired()}
</pre>
HTML;
$html .= '<h4>Destination Goal Steps</h4>';
$steps = $details->getSteps();
if (count($steps) == 0) {
$html .= '<p>No Steps Configured</p>';
} else {
foreach ($steps as &$step) {
$html .= <<<HTML
<pre>
Step Number = {$step->getNumber()}
Step Name = {$step->getName()}
Step URL = {$step->getUrl()}
</pre>
HTML;
}
}
return $html;
}
require_once 'google_api.php';
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
try {
$goals = $analytics->management_goals
->listManagementGoals('25788360',
'UA-25788360-20',
'~all');
} catch (Exception $e) {
print 'There was a general API error '
. $e->getCode() . ':' . $e->getMessage();
}
$html = '';
$items = $goals->getItems();
foreach ($items as &$goal) {
$html .= "
<pre>
Account ID = {$goal->getAccountId()}
Web Property ID = {$goal->getWebPropertyId()}
Internal Web Property ID = {$goal->getInternalWebPropertyId()}
Profile ID = {$goal->getProfileId()}
Goal Number = {$goal->getId()}
Goal Name = {$goal->getName()}
Goal Value = {$goal->getValue()}
Goal Active = {$goal->getActive()}
Goal Type = {$goal->getType()}
Created = {$goal->getCreated()}
Updated = {$goal->getUpdated()}
</pre>";
// Now get the HTML for the type of goal.
switch($goal->getType()) {
case 'URL_DESTINATION':
$html .= getUrlDestinationDetailsHtml(
$goal->getUrlDestinationDetails());
break;
case 'VISIT_TIME_ON_SITE':
$html .= getVisitTimeOnSiteDetailsHtml(
$goal->getVisitTimeOnSiteDetails());
break;
case 'VISIT_NUM_PAGES':
$html .= getVisitNumPagesDetailsHtml(
$goal->getVisitNumPagesDetails());
break;
case 'EVENT':
$html .= getEventDetailsHtml(
$goal->getEventDetails());
break;
}
echo $html;
}
It seems like you are using the Management API. This is meant for management purposes only. Getting and setting goals.
If you want data from goals as well you want to be looking at the Core Reporting API.
The available data for goals can be found here:
https://developers.google.com/analytics/devguides/reporting/core/dimsmets/goalconversions
The implementation guide can be found here:
https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide
I did not provide a full implementation example seeing that you already know how to setup the use of a Google API.
Good luck with you quest!
EDIT:
Added an example on how to use it:
<?php
$client = new apiAnalyticsService();
function queryCoreReportingApi() {
$optParams = array( //OPTINAL SETTINGS
'dimensions' => '', //A comma-separated list of Multi-Channel Funnels dimensions. E.g., 'mcf:source,mcf:medium'. (string)
'sort' => '', //A comma-separated list of dimensions or metrics that determine the sort order for the Analytics data. (string)
'filters' => '', //A comma-separated list of dimension or metric filters to be applied to the Analytics data. (string)
'start-index' => '', //An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. (integer, 1+)
'fields' => '', //Selector specifying which fields to include in a partial response.
'max-results' => '25'); //The maximum number of entries to include in this feed. (integer)
return $service->data_mcf->get(
$id, //Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics profile ID. (string)
'2010-01-01', //Start date for fetching Analytics data. All requests should specify a start date formatted as YYYY-MM-DD. (string)
'2010-01-15', //End date for fetching Analytics data. All requests should specify an end date formatted as YYYY-MM-DD. (string)
'ga:totalConversions', //A comma-separated list of Multi-Channel Funnels metrics. E.g., 'mcf:totalConversions,mcf:totalConversionValue'. At least one metric must be specified. (string)
$optParams);
}

Stuck with paginating youtube api playlist results, trying to calculate tha sum duration of all the videos in a playlist

I would like to make a little php snippet for my drupal site, which counts all the durations of all the videos in a youtube playlist.
I managed to find a good starting point here at this site, I made some changes, and it is almost good:
<?php
$playlist_id = "266DBEDBE6892C11";
$url = "https://gdata.youtube.com/feeds/api/playlists/".$playlist_id."?v=2&alt=json&start-index=1&max-results=50";
$data = json_decode(file_get_contents($url),true);
$info = $data["feed"];
$video = $info["entry"];
$nVideo = count($video);
$length = 0;
echo "Playlist Name: ".$info["title"]['$t'].'<br/>';
echo "Number of Videos (".$nVideo."):<br/>";
for($i=0;$i<200;$i++){
$temporary_length = $video[$i]['media$group']['yt$duration']['seconds'];
$length += $temporary_length;
echo "Lenght: ". $temporary_length ."<br/>";
}
echo "Length: " . $length ;
?>
My problem is, that I can't paginate, youtube only gives me maximum 50 results.
I tried with the start-index parameter, but that did not work for me.
I search through the youtube api pages, but I have no clue hot to do it. I am no programmer, this is what I could come up with with my limited programming knowledge.
What should I add to the code, to count all the videos in a playlist? Or If someone could help me with another snippet, that would be perfect also.
Thank you!
Sorry can't test this here, but taking into account what error you are getting I think you first need to check what data you have receieved back from youtube.
I also put in a friendly way for you to test the current page and requests per page.
<?php
//Configurable
$playlist_id = "266DBEDBE6892C11";
$results_per_request = 50;
$current_page = 1;
$start_index = $request_per_page * ($current_page - 1) + (($current_page > 1) ? 1 : 0);
$url = "https://gdata.youtube.com/feeds/api/playlists/".$playlist_id."?v=2&alt=json&start-index=".$start_index."&max-results=".$results_per_request;
$data = json_decode(file_get_contents($url),true);
if (is_array($data) && count($data) > 0)
{
$info = $data["feed"];
$video = $info["entry"];
$nVideo = count($video);
$length = 0;
echo "Playlist Name: ".$info["title"]['$t'].'<br/>';
echo "Number of Videos (".$nVideo."):<br/>";
for($i=0;$i<200;$i++){
$temporary_length = $video[$i]['media$group']['yt$duration']['seconds'];
$length += $temporary_length;
echo "Lenght: ". $temporary_length ."<br/>";
}
echo "Length: " . $length ;
}
else
{
echo "Youtube did not return any more results."
}
?>

Send a product's custom feature in order confirmation email

I want to send the "units per box" custom feature in my confirmation mails in prestashop.
Here's an example if what I want to do
$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1));
foreach(from=$features item=feature)
{
if ($feature.name == "Units per box")
{
$UnitsPerBox = $feature.value|escape:'htmlall':'UTF-8';
}
}
However I need to do this within a php file (PaymentModule.php) rather than a tpl file, so that code won't work.
If anybody could point me in the right direction of how to achieve this with php it'd be greatly appreciated.
EDIT:
I used the example code provided which seems to get inside the array but doesn't return any values
When I run some test code like this
$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1);
$UnitsPerBox .= '100';
foreach ($features as $feature)
{
$UnitsPerBox .= '200';
if ($feature->name == 'Units Per Box')
{
$UnitsPerBox .= htmlentities($feature->value, 'ENT_QUOTES', 'UTF-8');
$UnitsPerBox .= $feature->name;
}
else
{
$UnitsPerBox .= $feature->name;
$UnitsPerBox .= htmlentities($feature->name, 'ENT_QUOTES', 'UTF-8');
$UnitsPerBox .= htmlentities($feature->value, 'ENT_QUOTES', 'UTF-8');
}
}
I get this output: "100200200200200200"
Any help would be great, thanks.
Thanks,
Andrew
EDIT: Solution
Got it working in the end, thanks for the help
$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1);
foreach ($features as $feature)
{
foreach ($feature as $key => $value)
{
if($value == "Units per box")
{
$UnitsPerBox = $feature['value'];
}
}
}
$myprod = new Product($product['id_product']);
$features = $myprod->getFrontFeatures(1);
foreach ($features as $feature) {
if ($feature->name == 'Units per box') {
$UnitsPerBox = htmlentities($feature->value, 'ENT_QUOTES', 'UTF-8');
}
}
This looks like Smarty template code. In that case, the function you're looking for is htmlentities():
foreach($features as $feature)
{
if ($feature->name == "Units per box")
{
$UnitsPerBox = htmlentities($feature->value, ENT_QUOTES, 'UTF-8');
}
}
I have modified my file
classes/PaymentModule.php
I can print short and Long Description of the product, but I'm just not being able to put the features of the product on the order confirmation mail template, I came up with a solution using this page and also this https://www.prestashop.com/forums/topic/658353-15-add-products-features-in-order-confirmation-email/, using this last solution I was just able to print the ID of the order confirmation.
I added the following around line 353
$lesfeatures = Product::getFrontFeaturesStatic((int)$id_lang, `$product['id_product']);`
foreach ($lesfeatures as $key => $lafeature) {
$machin .= print_r($lafeature);
$machin .= $lafeature['id_feature'].'name:'.$lafeature['name'].'value:'.$lafeature['value'].'<br>';}
and then the following around line 400
<strong>'.$product['name'].(isset($product['attributes']) ? ' - '.$product['attributes'] : '').'</strong>'.$machin.'
That's when I just get the Order ID
This is my current working code around line 400 for printing descriptions
<strong>
Cantidad de Piezas: '.$product['quantity'].'
<br/>
'.$product['name'].(isset($product['attributes']) ? ' - '.$product['attributes'] : '').'
<br/>Descripcič´¸n: '.$product['description_short'].'
</strong>

Categories