i'm using laravel now i want to list all the google web fonts in my page using google font api
public function index(){
function get_google_fonts() {
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=!";
$result = json_response( $url );
$font_list = array();
foreach ( $result->items as $font ) {
echo $font;
}
return $font_list;
}
return view('website_settings');
}
i think it's not working, can anyone help me please!
because $font is an object you have to traverse.. try something like that
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=!";
$result = json_decode(file_get_contents( $url ));
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
return $font_list;
Related
I have build my own component in joomla and client wants now a friendly urls f.e
website.com/someplace/{product-id}-{product-name}. So i Build my own router like this.
function componentBuildRoute(&$query)
{
$segments = [];
if (isset($query['view'])) {
$segments[] = "szkolenie";
unset($query['view']);
}
if (isset($query['product_id'])) {
$productName = JFilterOutput::stringURLSafe(strtolower(getProductName($query['product_id'])));
$newName = $query['product_id'] . '-' . $productName;
$segments[] = $newName;
unset($query['product_id']);
}
return $segments;
}
and parse route function
function componentParseRoute($segments)
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item =& $menu->getActive();
$count = count($segments);
switch ($item->query['view']) {
case 'catalogue' : {
$view = 'training';
$id = $segments[1];
}
break;
}
$data = [
'view' => $view,
'product_id' => $id
];
return $data;
}
While on the end of buildroute function segments are ok I have exactly what I want that on the beginning of parse route I have something like
website.com/szkolenie/1-krakow <-- I dont know wtf is this krakow( I know it is city i Poland) but still where is it get from ? The getProductName function implementation is
function getProductName($productId)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('#__component_training.id as id, #__component_product' . name)
->from($db->quoteName('#__component_training'))
->where('#__s4edu_product.product_id = ' . $productId)
->leftJoin('#__component_product ON
#__component_training.product_id=#__component_product.product_id');
$training = $db->loadObject();
return trim($training->name);
}
So taking all this into consideration I think that something is happening between the buildRoute and parseRoute, something what filters the $segment[1] variable, but how to disable that and why is it happening ?
P.S
Please do not send me to https://docs.joomla.org/Joomla_Routes_%26_SEF
I already know all the tutorials on joomla website which contains anything with sef.
P.S.S
It is built on joomla 3.7.0
You do not have a product named "krakow" ?
If not you can try to remove the $productName from the build function, just to check if this "krakow" is added automaticaly or it's from the getProductName() function.
Also i noticed that you have an error i guess in the function getProductName()
->where('#__s4edu_product.product_id = ' . $productId)
It's should be
->where('#__component_product.product_id = ' . $productId)
SCENARIO : I allow to create posts from front-end. The form also has four image upload fields. I use the code pasted below for image attachments and setting the post thumbnail.
//insert attachments
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); //you will need to comment out this line if you use my solution
return $attach_id;//you will need to comment out this line if you use my solution
}
The post-thumbnail/featured image that is set through this code is the LAST image that is uploaded. I tried a google search for "set post thumbnail from frontend wordpress" and grazed through a lot of articles but none came close to what I am asking here. Majority of threads I came across at SE in regards to front-end posting, either talks about setting the featured image or about multiple uploads. I have also checked all the suggested questions which were prompted, while I was writing this question just to make sure if it has been asked before.
If it matters, here is the html that is used in the form, pretty standard.
<input type="file" name="image-one" id="image-one"/>
<input type="file" name="image-two" id="image-two"/>
<input type="file" name="image-three" id="image-three"/>
REQUEST : It would be great if I could get a solution that helps to assign any chosen image-input-field as a featured-image but at this moment, at least what I need to set the FIRST image input to be set as a featured-image/post-thumbnail. Kindly suggest a solution.
Bottomline is that I do not have an issue with setting post-thumbnail
but question is about having a choice to choose any of the uploaded
images as post-thumbnail or at least the first image, instead of the
last image as set by the current code.
PROGRESS REPORT :
Never know if it would help in cracking this issue. But when I print_($newupload), I get the id eg. 54287 ,of the last-image-input attachment that is saved as post-thumbnail.
This thread suggests a way to set a featured-image with the first image found in the post so I thought of working on that idea. But the code does not seem to work either.
$attachments = get_children(array(
'post_parent' => $pid,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'ID'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($pid, $attachment->ID);
break;
}
FINAL WORD : The code in the progress report momentarily gets the job done for me, that is.. setting the first image-file-input as a featured-image/post-thumbnail and I am not even sure if this is the best way to do this. I am still looking for a solution which could give a flexibility to choose any image-input-field as a featured-image. If you decide to use this feature remember to comment out the second last and third last lines from the original code.
Saving a post_meta with _thumbnail_id as meta_key and the attach_id as meta_value won't make that image a featured image, you can use wp_insert_attachment that will help you a lot in this. Make sure you read the codex and the examples there. The function should be used in conjunction with wp_update_attachment_metadata() and wp_generate_attachment_metadata() this way your feature image will be created properly by wordpress.
EDIT:
I've looked over your code and I'm gussing it's easier to use it then my schetch in this case. I've added a file count and a parameter to insert_attachment. Check this code let me know what happens.
Example:
<?php
//insert attachments
if ($_FILES) {
array_reverse($_FILES);
$i = 0;//this will count the posts
foreach ($_FILES as $file => $array) {
if ($i == 0) $set_feature = 1; //if $i ==0 then we are dealing with the first post
else $set_feature = 0; //if $i!=0 we are not dealing with the first post
$newupload = insert_attachment($file,$pid, $set_feature);
$i++; //count posts
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail if setthumb is 1
if ($setthumb == 1) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
?>
We can set post featured image from frontend using following function,
simple you need to call this function
post_imgs_update($new_post_id);
after creating new post. and add following function in functions.php
if ( ! function_exists( 'post_imgs_update' ) ) :
function post_imgs_update($new_post_id) {
$data = array();
$attachment_ids = array();
// code for save featured image
if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){ // here nonce text is "image_upload" you need to add in form
$files = reArrayFiles($_FILES['files']);
if(!empty($_FILES['files'])){
//$i = 0;
$set_featured_img = 0 ;
foreach( $files as $file ){
if( is_array($file) ){
$attachment_id = upload_user_file( $file, basename($file['name']) );
if ( is_numeric($attachment_id) ) {
if ($set_featured_img == '0') {
set_post_thumbnail($new_post_id, $attachment_id);
$set_featured_img++;
$attachment_ids[] = $attachment_id;
}
else{
$attachment_ids[] = $attachment_id;
}
}
}
}
//add to array
$mediaurl = array();
foreach ($attachment_ids as $img_id) {
$imgurl = wp_get_attachment_url( $img_id );
$image_gallery[$img_id] = $imgurl;
}
update_post_meta( $new_post_id, '_stw_property_multi_images', $image_gallery); // 2nd arg field key
}
}
else {
$data['status'] = false;
$data['message'] = __('Nonce verify failed','realestate');
}
return $new_post_id;
}
endif;
if ( ! function_exists( 'reArrayFiles' ) ) :
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
endif;
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
$attachurlarray = array();
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
return $attach_id;
}
I am hoping someone has some experience with the blueimp fileupload jquery plugin at : https://github.com/blueimp/jQuery-File-Upload
How to add the uploaded file name to database ?
In the options array (look for $this->options = array( )
and insert
'database' => 'database_name',
'host' => 'localhost',
'username' => 'user',
'password' => 'password',
Then after
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = new stdClass();
$file->name = $this->get_file_name($name, $type, $index, $content_range);
$file->size = $this->fix_integer_overflow(intval($size));
$file->type = $type;</code></pre>
Insert this code
//Start added coded
// prepare the image for insertion
$data = addslashes (file_get_contents($uploaded_file));
// get the image info..
$size = getimagesize($uploaded_file);
$file->upload_to_db = $this->add_img($data, $size, $name);
//end added code
and after the function handle_file_upload insert the following code to actually upload the image to the database.
function query($query) {
$database = $this->options['database'];
$host = $this->options['host'];
$username = $this->options['username'];
$password = $this->options['password'];
$link = mysql_connect($host,$username,$password);
if (!$link) {
die(mysql_error());
}
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die(mysql_error());
}
$result = mysql_query($query);
mysql_close($link);
return $result;
}
function add_img($data,$size,$name)
{
$add_to_db = $this->query("INSERT INTO your_database_name
(image_type ,image, image_size, file_name)
VALUES
('{$size['mime']}', '{$data}', '{$size[3]}', '{$name}')") or die(mysql_error());
return $add_to_db;
}
This will store the actual image in the database if you don't want that change the add_img($data,$size,$name) to add_img($size,$name) and just don't pass the $data variable. The $data variable should be stored as a medium or long blob.
You can also comment out the fileupload to directory stuff so you don't get errors if you don't what the images uploaded to a directory. This is in the protected function handle_file_upload
//comment out file upload stuff since storing in database
/*
if ($this->validate($uploaded_file, $file, $error, $index)) {
$this->handle_form_data($file, $index);
$upload_dir = $this->get_upload_path();
if (!is_dir($upload_dir)) {
mkdir($upload_dir, $this->options['mkdir_mode'], true);
}
$file_path = $this->get_upload_path($file->name);
$append_file = $content_range && is_file($file_path) &&
$file->size > $this->get_file_size($file_path);
if ($uploaded_file && is_uploaded_file($uploaded_file)) {
// multipart/formdata uploads (POST method uploads)
if ($append_file) {
file_put_contents(
$file_path,
fopen($uploaded_file, 'r'),
FILE_APPEND
);
} else {
move_uploaded_file($uploaded_file, $file_path);
}
} else {
// Non-multipart uploads (PUT method support)
file_put_contents(
$file_path,
fopen('php://input', 'r'),
$append_file ? FILE_APPEND : 0
);
}
$file_size = $this->get_file_size($file_path, $append_file);
if ($file_size === $file->size) {
$file->url = $this->get_download_url($file->name);
list($img_width, $img_height) = #getimagesize($file_path);
if (is_int($img_width) &&
preg_match($this->options['inline_file_types'], $file->name)) {
$this->handle_image_file($file_path, $file);
}
} else {
$file->size = $file_size;
if (!$content_range && $this->options['discard_aborted_uploads']) {
unlink($file_path);
$file->error = 'abort';
}
}
$this->set_additional_file_properties($file);
}
*/
I want to remove certain state/Province from magento 1.12.0.2 checkout (onestepcheckout) page like "American Samoa"
I tried changing the Data.php file in "/app/code/local/Mage/Directory/"
public function getRegionJson()
{
$exclude_regions = array ('AS','FM');
Varien_Profiler::start('TEST: '.__METHOD__);
if (!$this->_regionJson)
{
$cacheKey = 'DIRECTORY_REGIONS_JSON_STORE'.Mage::app()->getStore()->getId();
if (Mage::app()->useCache('config')) {
$json = Mage::app()->loadCache($cacheKey);
}
if (empty($json))
{
$countryIds = array();
foreach ($this->getCountryCollection() as $country)
{
$countryIds[] = $country->getCountryId();
}
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->load();
$regions = array();
foreach ($collection as $region) {
$rg = $region->getCode();
//if ($rg!='AL'){
if(!in_array($rg, $exclude_regions)) {
if (!$region->getRegionId()) {
continue;
}
$regions[$region->getCountryId()][$region->getRegionId()] = array(
'code' => $region->getCode(),
//'name' => $region->getName()
'name' => $this->__($region->getName())
);
}
}
$json = Mage::helper('core')->jsonEncode($regions);
if (Mage::app()->useCache('config')) {
Mage::app()->saveCache($json, $cacheKey, array('config'));
}
}
$this->_regionJson = $json;
}
Varien_Profiler::stop('TEST: '.__METHOD__);
return $this->_regionJson;
}
but did not have any luck, any help will be greatly appreciated on how to do this
Thank you in advance
The above code works fine, i just needed to flush the Magento cache storage.
I am having a facebook error on stream_publish call. I actually used an extension for Magento for Fconnect. Fconnect & Flogin is working fine. But it is requirement that when user place an order it should be posted on user's wall. For that I have implemented like this
document.observe('click', function(e){
if (e.element().match('a[rel^=facebook-connect]') || e.element().match('button[rel^=facebook-connect]')) {
e.stop();
FB.login(function(response){
if(response.status=='connected') setLocation('http://staging.mystore.com/facebook/customer_account/connect/');
}, {perms:"email,publish_stream"});
}
});
in Facebook Client file generateSignature method is like this
private function _generateSig($params_array)
{
Mage::log($params_array);
$str = '';
ksort($params_array);
foreach ($params_array as $k=>$v) {
$str .= "$k=$v";
}
$str .= $this->_secret;
Mage::log($str);
Mage::log('md5 sigs:: ' . md5($str));
return md5($str);
}
& My code that is calling the API is like this
$message = 'just placed an order on mystore.com';
$attachment = array(
'name' => "mystore",
'href' => 'http://www.mystore.com/',
'description' => 'New order on mystore.com',
'media' => array(array('type' => 'image',
'src' => 'http://www.mystore.com/skin/frontend/default/mystore/images/logo.png',
'href' => 'http://www.mystore.com/')));
$action_links = array( array('text' => 'Buy#mystore', 'href' => 'http://www.mystore.com/'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
try{
// if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id))
if($this->_getClient()->call( 'facebook.stream.publish',
array($message, $attachment, $action_links,
$this->_getClient()->users->getLoggedInUser(),
Mage::getSingleton('facebook/config')->getApiKey() )
) )
{
Mage::log( "Added on FB Wall" );
}
} catch(Exception $e)
{
Mage::log( "Exception in wall write" );
Mage::log($e);
}
After logging the Signature I found in log is
api_key=XXXXXXXXmethod=facebook.stream.publishsession_key=2.AQCm5fABfobInAS5.3600.1309352400.1-1000025660978090=just placed an order on mystore.comcall_id=1309345883.3068format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
I have never done any development on Facebook SO I have no Idea what to do? Please help me with solution. & let me know if u guys need any other info to understand this.
Oh yeah One more thing the Client File code that is calling Api (call method) its like this
private function _prepareParams($method, $params)
{
$defaultParams = array(
'api_key' => $this->_apiKey,
'call_id' => microtime(true),
'format' => 'JSON',
'v' => '1.0'
);
if($this->_sessionKey){
$defaultParams['session_key'] = $this->_sessionKey;
}
$params = array_merge($defaultParams, $params);
foreach ($params as $key => &$val) {
if (!is_array($val)) continue;
$val = Zend_Json::encode($val);
}
$params['method'] = $method;
if(isset($params['sig'])) {
unset($params['sig']);
}
$params['sig'] = $this->_generateSig($params);
return $params;
}
public function call($method, $args=array())
{
Mage::log($args);
$params = $this->_prepareParams($method, $args);
$client = self::_getHttpClient()
->setUri(self::FACEBOOK_REST_URI)
->setMethod(Zend_Http_Client::POST)
->resetParameters()
->setParameterPost($params);
try {
$response = $client->request();
} catch(Exception $e) {
throw new Mage_Core_Exception('Service unavaliable');
}
if(!$response->isSuccessful()) {
throw new Mage_Core_Exception('Service unavaliable');
}
$result = Zend_Json::decode($response->getBody());
//json decode returns float on long uid number? is_json check? old php?
if(is_float($result)){
$result = $response->getBody();
}
if(is_array($result) && isset($result['error_code'])) {
throw new Mage_Core_Exception($result['error_msg'], $result['error_code']);
}
return $result;
}
For calling API I used two ways $this->_getClient()->call( 'facebook.stream.publish',
& $this->_getClient()->call( 'stream_publish',
None of them are working
ok GUys I figure out the mistake
look at my code
format=JSONv=1.01={"name":"mystore","href":"http:\/\/www.mystore.com\/","description":"New order on mystore.com","media":[{"type":"image","src":"http:\/\/www.mystore.com\/skin\/frontend\/default\/mystore\/images\/logo.png","href":"http:\/\/www.mystore.com\/"}]}2=[{"text":"Buy#mystore","href":"http:\/\/www.mystore.com\/"}]3=1000025660978094=5070afefb42b162aff748f55ecf44d110d9e2a90117ee1704e2adb41f1d190fa
where u can see format=JSONv=1.01={....}2=[{.....}] the problem was I used numeric arrays for parameters. they should be associated arrays
like message={new order}attachment={....}
Once I fixed the associative array problem my code start working correctly
here is a link that'll give u detail about parameters to pass to stream.publish
http://schoolout.net/en/developers/view/39
Hope this will help somebody else too.