swrlapi: Invalid SWRL atom predicate 'Person' - owl

When running a SWRL rule I get in swrlapi Invalid SWRL atom predicate 'Person'.
Most help suggests things like adding "Person" to the ontology. I think I've done that, but I want to be sure.
My ontology is the turtle primer with a few modifications:
#prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
#prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
#prefix owl: <http://www.w3.org/2002/07/owl#> .
#prefix owl2: <http://www.w3.org/2006/12/owl2#> .
#prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
#base <http://example.com/owl/families#> .
###########################################
# Object properties
###########################################
<hasAncestor> rdf:type owl:ObjectProperty ,
owl:TransitiveProperty ,
owl2:IrreflexiveProperty .
<hasChild> rdf:type owl:ObjectProperty ;
rdfs:subPropertyOf <hasAncestor> ;
rdfs:domain <Person> ;
rdfs:range <Person> ;
owl:equivalentProperty <child> .
_:x0 rdf:type owl:Restriction ;
owl:onProperty <hasGender> ;
owl:hasValue <female> .
_:x1 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x0) .
<hasDaughter> rdf:type owl:ObjectProperty ;
rdfs:range _:x1 ,
<Person> ;
rdfs:domain <Person> ;
rdfs:subPropertyOf <hasChild> ;
rdfs:domain <Parent> ;
owl2:disjointObjectProperties <hasSon> .
<hasGender> rdf:type owl:ObjectProperty .
<hasHusband> rdf:type owl:ObjectProperty ;
owl:inverseOf <hasWife> .
<hasSon> rdf:type owl:ObjectProperty .
_:x3 rdf:type owl:Restriction ;
owl:onProperty <hasGender> ;
owl:hasValue <male> .
_:x4 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x3) .
<hasSon> rdfs:range _:x4 ;
rdfs:subPropertyOf <hasChild> ;
rdfs:range <Person> ;
rdfs:domain <Person> ,
<Parent> .
<hasSpouse> rdf:type owl:ObjectProperty ,
owl:SymmetricProperty ,
owl2:IrreflexiveProperty .
<hasWife> rdf:type owl:ObjectProperty ,
owl:InverseFunctionalProperty ,
owl:FunctionalProperty ,
owl2:AsymmetricProperty ,
owl2:IrreflexiveProperty ;
rdfs:domain <Person> ;
rdfs:range <Person> ;
rdfs:subPropertyOf <loves> ;
rdfs:range <Woman> ;
rdfs:subPropertyOf <hasSpouse> ;
rdfs:domain <Man> .
<loves> rdf:type owl:ObjectProperty ;
rdfs:domain <Person> .
###########################################
# Data properties
###########################################
<hasAge> rdf:type owl:DatatypeProperty ,
owl:FunctionalProperty ;
rdfs:domain <Person> ;
rdfs:range xsd:integer ;
owl:equivalentProperty <age> .
###########################################
# Classes
###########################################
<Adult> rdf:type owl:Class .
_:x5 rdf:type owl2:DataRange ;
owl2:onDataRange xsd:integer ;
owl2:minInclusive "21"^^xsd:int .
_:x6 rdf:type owl:Restriction ;
owl:onProperty <hasAge> ;
owl:someValuesFrom _:x5 .
_:x7 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x6) .
<Adult> owl:equivalentClass _:x7 ,
<Grownup> .
<Child> rdf:type owl:Class .
_:x8 rdf:type owl2:DataRange ;
owl2:onDataRange xsd:integer ;
owl2:minInclusive "21"^^xsd:int .
_:x9 rdf:type owl:Restriction ;
owl:onProperty <hasAge> ;
owl:someValuesFrom _:x8 .
_:x10 rdf:type owl:Class ;
owl:complementOf _:x9 .
_:x11 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x10) .
<Child> owl:equivalentClass _:x11 .
<CivilMarriage> rdf:type owl:Class .
<Man> rdf:type owl:Class ;
rdfs:subClassOf <Parent> .
_:x12 rdf:type owl:Restriction ;
owl:onProperty <hasGender> ;
owl:hasValue <male> .
_:x13 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x12) .
<Man> owl:equivalentClass _:x13 .
<Marriage> rdf:type owl:Class .
_:x14 rdf:type owl:Class ;
owl:unionOf (<CivilMarriage> <ReligiousMarriage>) .
<Marriage> owl:equivalentClass _:x14 .
<Narcissist> rdf:type owl:Class .
_:x15 rdf:type owl2:SelfRestriction ;
owl:onProperty <loves> .
_:x16 rdf:type owl:Class ;
owl:intersectionOf (_:x15 <Person>) .
<Narcissist> owl:equivalentClass _:x16 .
<Parent> rdf:type owl:Class ;
rdfs:subClassOf <Parent> .
_:x17 rdf:type owl:Restriction ;
owl:onProperty <hasChild> ;
owl2:onClass <Person> ;
owl:minCardinalityQ "1"^^xsd:nonNegativeInteger .
_:x18 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x17) .
<Parent> owl:equivalentClass _:x18 .
<Person> rdf:type owl:Class ;
rdf:about "Person"^^xsd:string ;
rdf:ID "Person"^^xsd:string ;
rdfs:label "Person"^^xsd:string .
_:x19 rdf:type owl:Class ;
owl:oneOf (<female> <male>) .
_:x20 rdf:type owl:Restriction ;
owl:onProperty <hasGender> ;
owl:allValuesFrom _:x19 .
_:x21 rdf:type owl:Restriction ;
owl:onProperty <hasGender> ;
owl:cardinality "1"^^xsd:nonNegativeInteger .
_:x22 rdf:type owl:Restriction ;
owl:onProperty <hasAge> ;
owl:cardinality "1"^^xsd:nonNegativeInteger .
_:x23 rdf:type owl:Class ;
owl:intersectionOf (_:x20 _:x21 _:x22) .
<Person> rdfs:subClassOf _:x23 .
<ReligiousMarriage> rdf:type owl:Class ;
owl:disjointWith <CivilMarriage> .
<Teenager> rdf:type owl:Class .
_:x24 rdf:type owl2:DataRange ;
owl2:minInclusive "13"^^xsd:int ;
owl2:maxExclusive "20"^^xsd:int ;
owl2:onDataRange xsd:integer .
_:x25 rdf:type owl:Restriction ;
owl:onProperty <hasAge> ;
owl:someValuesFrom _:x24 .
_:x26 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x25) .
<Teenager> owl:equivalentClass _:x26 .
<Woman> rdf:type owl:Class ;
rdfs:subClassOf <Parent> .
_:x27 rdf:type owl:Restriction ;
owl:onProperty <hasGender> ;
owl:hasValue <female> .
_:x28 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x27) .
<Woman> owl:equivalentClass _:x28 .
<YoungChild> rdf:type owl:Class .
_:x29 rdf:type owl:Class ;
owl:unionOf (<Adult> <Teenager>) .
_:x30 rdf:type owl:Class ;
owl:complementOf _:x29 .
_:x31 rdf:type owl:Class ;
owl:intersectionOf (<Person> _:x30) .
<YoungChild> owl:equivalentClass _:x31 .
###########################################
# Individuals
###########################################
# Bill
_:x32 rdf:type owl:Class ;
owl:complementOf <Narcissist> .
<Bill> rdf:type _:x32 ;
<hasAge> "13"^^xsd:integer ;
<hasGender> <male> .
# Ellen
_:x33 rdf:type owl2:DataRange ;
owl2:minInclusive "15"^^xsd:int ;
owl2:onDataRange xsd:integer ;
owl2:maxInclusive "21"^^xsd:int .
_:x34 rdf:type owl:Restriction ;
owl:onProperty <hasAge> ;
owl:someValuesFrom _:x33 .
<Ellen> rdf:type _:x34 .
# Emily
_:x35 rdf:type owl2:DataRange ;
owl:oneOf ("39"^^xsd:integer "49"^^xsd:integer) .
_:x36 rdf:type owl:Restriction ;
owl:onProperty <hasAge> ;
owl:someValuesFrom _:x35 .
<Emily> rdf:type _:x36 .
# Jack
_:x37 rdf:type owl2:NegativeDataPropertyAssertion ;
rdf:subject <Jack> ;
rdf:predicate <hasAge> ;
rdf:object "53"^^xsd:integer .
# Jeff
_:x38 rdf:type owl:Restriction ;
owl:onProperty <hasChild> ;
owl:cardinality "2"^^xsd:nonNegativeInteger .
<Jeff> rdf:type _:x38 ;
<hasAge> "77"^^xsd:integer ;
<hasChild> <Ellen> ;
<hasWife> <Emily> ;
<loves> <Jeff> ;
<hasChild> <Jack> .
# John
<John> rdf:type <Person> ;
<hasDaughter> <Susan> ;
<hasGender> <male> ;
<hasWife> <Mary> ;
<hasSon> <Bill> ;
<hasAge> "33"^^xsd:integer ;
owl:sameAs <Jack> .
# Mary
<Mary> <hasAge> "31"^^xsd:integer ;
<hasGender> <female> ;
<hasSon> <Bill> ;
<hasDaughter> <Susan> .
# Susan
<Susan> <hasAge> "8"^^xsd:integer ;
<hasGender> <female> .
<female> owl:sameAs <feminine> .
<male> owl:sameAs <masculine> .
###########################################
# General axioms
###########################################
_:x39 rdf:type owl:AllDifferent;
owl:distinctMembers (<John> <Mary> <Bill> <Susan>).
_:x40 rdf:type owl:AllDifferent;
owl:distinctMembers (<Jeff> <Emily> <Jack> <Ellen> <Susan>) .
_:x41 rdf:type owl:AllDifferent;
owl:distinctMembers (<male> <female>) .
# The following representation passes validation, but does not conform to the Turtle specification.
#(<hasSpouse> <hasSon>) rdfs:subPropertyOf <hasSon> .
_:x42 rdf:first <hasSon> ;
rdf:rest rdf:nil .
_:x43 rdf:type rdf:List ;
rdf:first <hasSpouse> ;
rdf:rest _:x42 ;
rdfs:subPropertyOf <hasSon> .
# The following representation passes validation, but does not conform to the Turtle specification.
#(<hasSpouse> <hasDaughter>) rdfs:subPropertyOf <hasDaughter> .
_:x44 rdf:first <hasDaughter> ;
rdf:rest rdf:nil .
_:x45 rdf:type rdf:List ;
rdf:first <hasSpouse> ;
rdf:rest _:x44 ;
rdfs:subPropertyOf <hasDaughter> .
I've done the following to try to fix it:
I modified the f prefix to be the base prefix because I thought perhaps my Turtle rules would only recognize the base prefix in the ontology.
Based on the comment on the answer here I added manager.getOntologyFormat(ontology).asPrefixOWLOntologyFormat().setDefaultPrefix(base + "#") after I define my ontology and before I add the rule engine.
After reading this I added rdf:about rdf:ID and rdfs:label to the declaration of "Person"
Yet, I still get Invalid SWRL atom predicate 'Person' when I run the following command and infer:
SWRLRule rule = ruleEngine.createSWRLRule("IsSenior-Rule",
"Person(?p) ^ hasAge(?p, ?age) ^ swrlb:greaterThan(?age, 60) -> Senior(?p)");

Related

add a span tag to each letter, space, character from title

I try to add span tag to each letter, space, character from title. When I use str_split then special characters are converted to another format.
if ( !function_exists( 'my_title' ) ):
function my_title( $str = '' ) {
$output = '';
$str = empty( $str ) ? wp_strip_all_tags( get_the_title() ) : $str;
if ( empty( $str ) ) {
return $output;
}
$i = 1;
foreach( str_split ( $str ) as $letter ) if ( $i++ <= 12 ) {
if ( !empty( $letter ) ) {
$output .= '<span>' . $letter . '</span>';
}
};
return wp_kses_post( $output );
}
endif;
echo my_title('Page title - with dash');
The problem is likely because of the wptexturize() function which is being applied on post titles, where certain characters such as - (dashes) are automatically converted to HTML entities such as – for "beautiful" dashes.
So try this, which worked for me:
if ( !function_exists( 'my_title' ) ):
function my_title( $str = '', $max_chars = 12 ) {
$output = '';
remove_filter( 'the_title', 'wptexturize' );
$str = empty( $str ) ? wp_strip_all_tags( get_the_title() ) : $str;
add_filter( 'the_title', 'wptexturize' );
if ( empty( $str ) ) {
return $output;
}
$str = html_entity_decode( $str, ENT_NOQUOTES, 'UTF-8' );
for ( $i = 0; $i < min( mb_strlen( $str ), $max_chars ); $i++ ) {
if ( $letter = mb_substr( $str, $i, 1 ) ) {
$output .= '<span>' . $letter . '</span>';
}
}
return wp_kses_post( $output );
}
endif;
UPDATE — Notes:
Sorry #michael, I should've mentioned that I also modified the my_title() function to use the html_entity_decode(), mb_strlen(), and mb_substr() functions, so that HTML entities are properly handled. (str_split() is not able to properly handle multi-byte encoded string — for example, HTML entities such as the –)
Hence, even if the wptexturize() function is applied on the post title, the modified my_title() function should have no problems of handling the – and other HTML entities (or special characters like that). So you can, if you want, change this:
remove_filter( 'the_title', 'wptexturize' );
$str = empty( $str ) ? wp_strip_all_tags( get_the_title() ) : $str;
add_filter( 'the_title', 'wptexturize' );
to this:
$str = empty( $str ) ? wp_strip_all_tags( get_the_title() ) : $str;
i.e. it's not necessary to remove the wptexturize hook. Just in case if you'd like to keep the "beautiful" dashes and other special characters converted by the wptexturize() function. =)

CakePHP 3 : Hybriauth config does not exist on the given path

I am working on CakePHP 3 project where I have to add social login.
For that I'm using HybridAuth following the tutorial from Here
Now When I access http://website.com/users/social/Facebook I get error as
Hybriauth config does not exist on the given path.
My UsersController is
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
/**
* Users Controller
*
* #property \App\Model\Table\UsersTable $Users
*/
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['register','logout','social','social_redirect']);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password'));
}
}
public function social($provider)
{
/* Include the config file */
require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'config.php');
require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'Hybrid' . DS . 'Auth.php');
/* Initiate Hybrid_Auth Function */
$hybridauth = new \Hybrid_Auth($config);
$authProvider = $hybridauth->authenticate($provider);
$user_profile = $authProvider->getUserProfile();
/* Modify here as per need. This is for demo */
if ($user_profile && isset($user_profile->identifier)) {
echo "<b>Name</b> : " . $user_profile->displayName . "<br />";
echo "<b>Profile URL : </b>" . $user_profile->profileURL . "<br />";
echo "<b>Image : </b>" . $user_profile->photoURL . "<br />";
echo "<img src='" . $user_profile->photoURL . "'<br />";
echo "<b>Email : </b>" . $user_profile->email . "<br />";
echo "<br /> <a href='logout.php'>Logout</a>";
}
exit;
/* Example demo for FB authorize Action */
#Facebook authorize
if ($this->request->params['pass'][0] == 'Facebook') {
if ($user_profile && isset($user_profile->identifier)) {
$this->authorize_facebook($user_profile);
}
}
}
public function social_redirect()
{
$this->layout = false;
$this->autoRender = false;
require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'config.php');
require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'Hybrid' . DS . 'Auth.php');
require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'Hybrid' . DS . 'Endpoint.php');
$hybridauth = new \Hybrid_Auth($config);
\Hybrid_Endpoint::process();
}
public function authorize_facebook($user_profile)
{
$provider = 'Facebook';
$provider_uid = $user_profile->identifier;
$userExist = $this->Users->find('all')->where(['Users.provider' => $provider, 'Users.provider_uid' => $user_profile->identifier])->first();
if ((isset($userExist)) && ($userExist)) {
$session = $this->request->session();
$session->delete('auth_sess_var');
$session->destroy();
$this->Auth->setUser($userExist->toArray());
$session->write('auth_sess_var', $userExist);
return $this->redirect($this->Auth->redirectUrl());
} else {
/* Create new user entity */
$user = $this->Users->newEntity();
$tmp_hash = md5(rand(0, 1000));
$tmp_id = time();
/* Save individual data */
$user->tmp_id = $tmp_id;
$firstName = (!empty($user_profile->firstName)) ? $user_profile->firstName : "";
$lastName = (!empty($user_profile->lastName)) ? $user_profile->lastName : "";
$user->name = $firstName . ' ' . $lastName;
// $user->username = (!empty($user_profile->firstName) && !empty($user_profile->lastName)) ? strlolower($user_profile->firstName) . "." . strtolower($user_profile->lastName) : "";
// $user->avatar = (!empty($user_profile->photoURL)) ? $user_profile->photoURL : "";
// $user->role = "public";
$user->provider = $provider;
$user->provider_uid = $user_profile->identifier;
$user->email = !empty($user_profile->email) ? $user_profile->email : "";
$user->password = $user_profile->identifier;
// $user->confirm_password = $user_profile->identifier;
$user->tmp_hash = $tmp_hash;
$user->verified = (!empty($user_profile->emailVerified)) ? 1 : 0;
$user = $this->Users->patchEntity($user, $this->request->data);
$this->Users->save($user);
$userDetails = $this->Users->find('all')
->where(['Users.provider' => $provider, 'Users.provider_uid' => $user_profile->identifier])->first();
/* Destroy previous session before setting new Session */
$session = $this->request->session();
$session->delete('auth_sess_var');
$session->destroy();
/* Set user */
$this->Auth->setUser($userDetails->toArray());
$session->write('auth_sess_var', $userDetails);
return $this->redirect($this->Auth->redirectUrl());
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
}
I have installed HybridAuth : version 2.5.1 using composer and its location is
| / root
|- vendor
|- hybridauth
|- hybridauth
|- hybridauth
|- Hybrid (directory)
|- Auth.php
|- ...
|- config.php
|- index.php
content of config.php
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
// ----------------------------------------------------------------------------------------
// HybridAuth Config file: http://hybridauth.sourceforge.net/userguide/Configuration.html
// ----------------------------------------------------------------------------------------
return
array(
"base_url" => "http://website.com/users/social-redirect/",
"providers" => array(
// openid providers
"OpenID" => array(
"enabled" => true
),
"Yahoo" => array(
"enabled" => true,
"keys" => array("key" => "", "secret" => ""),
),
"AOL" => array(
"enabled" => true
),
"Google" => array(
"enabled" => true,
"keys" => array("id" => "", "secret" => ""),
),
"Facebook" => array(
"enabled" => true,
"keys" => array("id" => "id", "secret" => "key"),
"trustForwarded" => false
),
"Twitter" => array(
"enabled" => true,
"keys" => array("key" => "", "secret" => ""),
"includeEmail" => false
),
// windows live
"Live" => array(
"enabled" => true,
"keys" => array("id" => "", "secret" => "")
),
"LinkedIn" => array(
"enabled" => true,
"keys" => array("key" => "", "secret" => "")
),
"Foursquare" => array(
"enabled" => true,
"keys" => array("id" => "", "secret" => "")
),
),
// If you want to enable logging, set 'debug_mode' to true.
// You can also set it to
// - "error" To log only error messages. Useful in production
// - "info" To log info and error messages (ignore debug messages)
"debug_mode" => false,
// Path to file writable by the web server. Required if 'debug_mode' is not false
"debug_file" => "",
);
What is wrong with the code ?
this is the way to remove error:
in users controller where you call(require) config.php
require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'config.php');
you need to store that what you require in variable $config:
$config = require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'config.php');
best regards

CakePHP image upload component

I would like to know how I can improve this CakePHP 3.0 Component (inside folder controller)
1st: to use external libs (stored on vendor folder) I'm using the require keyword and include the class using use keyword, like this:
require_once(ROOT . DS . 'vendor' . DS . 'CakePHP-ImageTool-Component' . DS . 'ImageTool.php');
and
use ImageTool;
How I can put this on CakePHP 3 pattern ?
2nd: in method saveFileLFS I'm using true or false to flag OK.
How I can improve this check ?
<?php
namespace App\Controller\Component;
require_once(ROOT . DS . 'vendor' . DS . 'CakePHP-ImageTool-Component' . DS . 'ImageTool.php');
use Burzum\FileStorage\Lib\StorageManager;
use Cake\Controller\Component;
use ImageTool;
class UploadFileComponent extends Component
{
function resizeImage($settings)
{
$status = ImageTool::resize([
'input' => $settings['input'],
'output' => $settings['output'],
'width' => $settings['width'],
'height' => $settings['height'],
'mode' => $settings['mode']
]);
return $status;
}
public function saveFileLFS($stringSeparator, $storeName, $productName)
{
$key = $storeName . $stringSeparator . $productName . $stringSeparator .
$this->request->data['Media']['file']['name'];
if(StorageManager::adapter('Local')->write($key,
file_get_contents($this->request->data['Media']['file']['tmp_name']))){
return true;
}else
{
return false;
}
}
}

Cakephp : how can i retrieve my media files from the folder to display on my view page

i am working on a Cakephp 2.x .. what i have done right now is .. i am displaying a user a form in which i have given him the option to upload an audio file .. so i have taken the file from the user .. i am saving the file into the app/uploads folder .. and the path into the database ... now the problem is i dont how can i know retrieve my audio file and show them into my view page
here is my uploading function
public function audio(){
if ($this->request->isPost()){
$this->loadModel('Audio');
$file = $this->request->data['Audio']['file'];
$idUser = $this->Auth->user('idUser');
if ($file['error'] === UPLOAD_ERR_OK) {
$id = String::uuid();
$name =$file['name'];
$folder_url = APP.'uploads/'.$idUser;
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
move_uploaded_file($file['tmp_name'], $folder_url.DS.$name);
$this->request->data['Audio']['User_id'] = $idUser;
$this->request->data['Audio']['filename'] = $file['name'];
$this->request->data['Audio']['filesize'] = $file['size'];
$this->request->data['Audio']['filemime'] = $file['type'];
$this->Audio->save($this->request->data);
return true;
}
}
return false;
}
public function showAllAudioFiles(){
}
now the file of particular user has stored into this folder app/uploads/23/file.mp3
Answer:
Assuming you only have one file per user, you jsut need to find the database record and construct the path from that:
public function showAllAudioFiles(){
$record = $this->Audio->find('first', array('conditions' => array('User_id' => $this->Auth->user('idUser')));
$file = APP . 'uploads' . DS . $this->Auth->user('idUser') . DS . $record['Audio']['filename'] . '.' . $record['Audio']['filemime'];
$this->set('file', $file);
}
If a user can have multiple files:
public function showAllAudioFiles(){
$records = $this->Audio->find('all', array('conditions' => array('User_id' => $this->Auth->user('idUser')));
$files = array();
foreach ($records as $record) {
$files[] = APP . 'uploads' . DS . $this->Auth->user('idUser') . DS . $record['Audio']['filename'] . '.' . $record['Audio']['filemime'];
}
$this->set('files', $files);
}
Now the $file variable will contain a string of the format app/uploads/23/file.mp3, for example. Or $files will be an array of those strings.
Suggestion:
Doing it the proper 'Cake' way, you would just retrieve the records and echo them using the media method of HtmlHelper:
ACTION:
public function showAllAudioFiles(){
$record = $this->Audio->find('first', array('conditions' => array('User_id' => $this->Auth->user('idUser')));
$this->set('file', $record);
}
VIEW:
echo $this->Html->media($file['Audio']['filename'] . '.' . $file['Audio']['filemime'],
array('pathPrefix' => 'uploads' . DS . $file['Audio']['User_id']
);
This should output something like this:
<audio src="/uploads/23/file.mp3"></audio>
Creating a link to the file
Edit: For links to files, just use HtmlHelper's link method:
echo $this->Html->link($file['Audio']['filename'], WWW_ROOT . DS . 'uploads' . DS . $file['Audio']['User_id'] . DS . $file['Audio']['filename'] . DS . $file['Audio']['filemime']);
HtmlHelper::media

cakephp unable to load a mobile view

I am trying to load a separate mobile view and having a problem.
I can get my mobile layout to work but not the view.
I was using this question as a reference and I am running cakephp 2.1
CakePHP website mobile version
I am not sure how to structure my mobile views?
Is it /app/View/name/mobile/view.ctp or
/app/View/mobile/name/view.ctp or something else. I have been going in circles trying to figure this out. Any suggestions.
My AppController.php
Before Filter
public function beforeFilter() {
/* mobile layout testing */
if ($this->request->isMobile()){
$this->is_mobile = true;
$this->set('is_mobile', true );
$this->autoRender = false;
} else {
$this->set('is_mobile', false );
}
}
After Filter (shortened)
function afterFilter() {
$view_file = file_exists(
"/var/www" .
$this->webroot .
"app" . DS .
'View' . DS .
$this->name . DS .
'mobile/' .
$this->action .
'.ctp'
);
$layout_file = file_exists(
"/var/www" .
$this->webroot .
"app" . DS .
'View' . DS .
'Layouts' . DS .
'mobile/' .
$this->layout .
'.ctp'
);
if($view_file || $layout_file){
$this->render(
$this->action,
($layout_file?'mobile/':'').$this->layout,
($view_file?'mobile/':'').$this->action
);
}
}
In previous version(s) of CakePHP, $this->render() had three parameters, but in 2.x and beyond, it only has 2:
CakePHP 1.3 API for Controller render() - has 3 parameters:
http://api13.cakephp.org/class/controller#method-Controllerrender
CakePHP 2.0 API for Controller render() - has only 2 parameters:
http://api20.cakephp.org/class/controller#method-Controllerrender
Becuase of that, your answer utilizing only 2 parameters works much better than your attempt with 3. :)
(The CakePHP Book still incorrectly states that there are 3 parameters, so - I certainly don't blame you for trying as it's mentioned - had to look it up in more detail to find this out)
I ended up doing this below. My view folders now check for a mobile folder and load the view if it exists.
function afterFilter() {
// if in mobile mode, check for a valid view and use it
if (isset($this->is_mobile) && $this->is_mobile) {
$has_mobile_view_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . $this->name . DS . 'mobile' . DS . $this->action . '.ctp' );
$has_mobile_layout_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . 'Layouts' . DS . 'mobile' . DS . $this->layout . '.ctp' );
$view_file = ( $has_mobile_view_file ? 'mobile' . DS : '' ) . $this->action;
$layout_file = ( $has_mobile_layout_file ? 'mobile' . DS : '' ) . $this->layout;
$this->render( $view_file, $layout_file );
}
}

Resources