Popular just now

ad1

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Drupal 7 Views: Getting User and Node Reference ID from row using PHP

Drupal views is my default system for creating sites where an administrator or webmaster can configure a website after it has been developed. Unfortunately the community has misled many into believing that anything can be done using Views, Rules and a handful of popular modules without coding. This is definitively not true! And even if you can code it is a dangerous road to walk.

So here's my latest gripe. Connecting User and Node References, counting references and displaying the right information.
If you try to get the node id or user id from a reference it is not available in the $row variable as it should be. Ask the programmer why because I have no idea what this variable is good for otherwise. The output from it is:

stdClass Object
(
    [field_tutor] => 18
    [field_school] => 7
    [field_school_year] => 18
    [field_student] => 18
    [field_tutor_1] => 18
    [php] => 
)

Referenced field values are the node id of the parent and not the value that actually connects the information to the node or user content. The information is available though in the $data variable.

print $data->_field_data['nid']['entity']->field_student['und'][0]['nid']; // note nid not "value"
print $data->_field_data['nid']['entity']->field_tutor['und'][0]['uid']; // note uid not "value"

This took me about three days of hunting and frustration (along with a good portion of trial and error) and cost me a deadline. So posting it here might save you the same because there is no straight forward answer about this even from the Fields API creator or the Views team.

Update PHP to the latest version in Centos VPS

When you use a server image to create a VPS not everything is the latest or best version. So here's the steps for updating PHP to the latest release, which at this time is versio 5.4. While you could this manually adding in the repositories available from the community is easier to maintain.

wget http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
rpm -Uvh remi-release-5*.rpm epel-release-5*.rpm


EPEL
Extra Packages for Enterprise Linux (EPEL) is a
volunteer-based community effort from the Fedora project to create a repository of high-quality add-on packages for Red Hat Enterprise (RHEL) and its compatible spin-offs such as CentOS or Scientific Linux. Fedora is the upstream of RHEL and add-on packages for EPEL are sourced from the Fedora repository primarily and built against RHEL.



REMI
This is a repository created by Remi Collet with the aim to give support for old Fedora releases to allow them to install recent software, also it gives you the ability to have your CentOS/RHEL systems with the latest software available in the net.

Update PHP to the latest one in the repository



yum --enablerepo=remi update php php-*
/etc/init.d/httpd restart

How to build a PHP extension


The ext_skel script

A PHP extension is composed of several files common to all extensions. As the details of many of those files are similar from extension to extension, it can be laborious to duplicate the content for each one. Fortunately, there is a script which can do all of the initial setup for you. It's called ext_skel, and it's been distributed with PHP since 4.0.


Compiling PHP on Windows 7 with VC9

I just tried this in Windows 7 so here are some of my notes. I am writing this up because it prevents me from having to hunt down solutions by searching for hours. The answers are on Google but they are spread around. This is a one stop list of solutions to common errors encountered when compiling PHP on Windows.


What is the best PHP CMS?

I am probably going to take a lot of heat for saying this but.... not one of the top 6 most popular CMS systems is "the best". Being the best stopped being a priority with these systems long ago. They are the best at only one thing, being popular and that's it.

Beginning PHP: Besides PHP, Javascript, Jquery and Mysql what else should I learn?

Ok,  here's my quick answer:

If you want to continue to learn for the future you should learn a language that has true parallel or concurrency support.  The onslaught mobile devices is only going to increase and soon the only way for any web server including those in the cloud to survive will be concurrency, parallel programming and distributed processing.

Beginning PHP: What is MVC?

MVC (model=logic, view=output, controller=input) is one of the most popular patterns in PHP but it is not necessary. If you are using procedural techniques which most beginners do then MVC is not something you want to use at the moment. 

The order of learning that is best is procedural coding, object oriented programming and then patterns. If you are coming from java this can be changed a bit because java forces OOP. So continue to use OOP in PHP and then learn the PHP style of patterns. 

The one thing that beginners seem to never do is read. PHP is so easy to learn so the ritual of reading before doing is dropped. Try downloading a PHP manual (recommend chm version for protability ) in your mother tongue and at least scan over the examples and comments in it. The area you want to concentrate most on is architecture. Using procedural code without an understandable architecture (can be MVC style but is not a requirement) is called spagetti code, something all good programmers try to avoid.

Internationalizion and Localization of your web application with TMX

 A few years ago I wrote a white paper and then an article on internationalization of websites. At the time there was not much information available on this subject. Now today I find that the same situation exists. There are no real sources or community activity surrounding localization and internationalization or (i18n and il0n).

The previous weeks for me have been difficult as I tried to repair a clients website and implement a multi-language website in Drupal. My discovery was that  there  has been no increase in effort to make internationalization easy and flexible in content management systems. They all are the same and some worse at handling content, layout and navigation in more languages than english.

In my article I discuss the use of HTML files for translation and localization of content. I was unaware that there was in fact an effort to utilize XML as a medium for internationalization called TMX . Although it seems like the movement has died out the idea is still a good one and should not be ignored for lack of evangelistic efforts of web developers. You can still find good information on the standard and there are parsers for PHP and Java availble as open source.

So it's time to revisit the world of internationalization and write a new up-to-date article about i18n technology and best practices.

It also seems that there is no community for i18n or efforts being promote by other communities so I think I'll start one. After all the times I'm brought in to projects where there has been no research done before development of a multi-language website in Drupal I believe there is still a need educate and inform project managers  and solution architects. They need to add internationalization and localization to their specs and requirements. They need to give i18n and i10n top priority when making decisions on what software to use.

One of the hightlights of TMX is that it allows translations to be re-used in different software packages and applications. Imagine if you will that you have a translation written for a Wordpress blog and you would like to re-use it in Drupal. It as simple as creating a module using one of PHP's XML parsers and dropping the file in.



OwnCloud vs. (Drupal + SabreDav)

I have not had any luck in adapting OwnCloud because of the lack of community knowledge and documentation. So I took some time to strip it down to its components. In the end OwnCloud just seems to be Web GUI for SabreDav. After a little hunting and research I found that I could get a more robust and customizable solution by using Drupal as frontend (authorization, uploads, CalDav UI) for my own SabreDav server.

Both Drupal and SabreDav have enough documentation, community and interest by php developers to get me over any obstacles I believe. SabreDav has an excellent OOP plugin system and I found some sandbox code for Drupal SabreDav and CalDav modules.

The only real difference I can find would be that OwnCloud uses Mirall and another protocol to sync things.

Anyone know of any really big differences or missing features that would arise from doing this? Am I wrong in thinking that OwnCloud is a wrapper for SabreDAv?

OwnCloud is OK but not "Enterprise" level

I posted this to the OwnCloud mailing lists a few days ago. So far I have not gotten any answer other than "read the ( non-existent) documentation".

So how does it work? There are no development documents, blog post or anything in the mailing list about how OwnCloud works. Granted it is an open source project and anyone can join in but we need a starting point. I have yet to find anything on the API, architecture or even comments in code that would allow to do more than just stare at the screen of my IDE in abject ignorance. Worse I can't fix anything that is broken because I have no idea where to go to find anything.


I have looked at the wiki, github documentation, googled 20 pages down and searched through the mailing lists. Nada, nothing, zip.

It seems to me I have been here a hundred times before. A company promotes their software as being open source. They want "community help" but they obfuscate everything about the software by hiding critical information on it's internals. Worse, the only way of getting information is to purchase support which would not be necessary if proper documentation was available.  It's a form of disguised software protectionism that I really despise. If you have ever read any of my previous blogs you know that I will write about such things until they end. Check out the Simple Machines Forum articles I wrote ( they are somewhere in Google ) which lead to them finally changing (http://www.simplemachines.org/about/opensource.php) their screwed up interpretation of open source. Though they still have not gotten it completely as shown by the conflict in the first and third statements of their license amendments.

  1. Retain the entire Simple Machines copyright and licensing notice in every file.
  2. Make clear that the changed product is not the same as the original Simple Machines software (SMF or any other product).
  3. Do not use the Simple Machines name (or the names of any Simple Machines contributors) to endorse or promote the modified software.
Ahh well, it is at least a partial victory if not a total awakening.  I have a feeling that I will have to use the same activism to bring OwnCloud into the reality of ( "community edition" does not mean open source ) what the spirit of open source truly means.

OwnCloud is garnering financing, promoting their services and gaining popularity by blowing the open source horn. While they may be giving out free source code it is by no means in the spirit of open source.  The label "community edition" is the tell. How many times have I seen those words and believed that a company is serious about open source? Not once.
OwnCloud,  If you want help with promoting, using and developing for your software then you are going to have to come up with more than a few dead links and blank pages in a wiki.

OwnCloud is great for the end user and might satisfy many companies in it's basic form. But enterprise level open source software it is not. There are not enough pluses to offset the minuses caused by a lack of information and community involvement depends on this in the beginning.

So far OwnCloud is a black box ( or dark cloud you might say ) and I am not impresssed. But I am open to change. So hopefully someone in the core or development group has enough time to swing me to the otherside by providing some real basics on how to customize and develop apps for OwnCloud.

Owncloud stuff: 1) login screen

Own cloud stuff:

I have a problem with my user_saml app. 

The problem:  
I used some javascript code on my apps/user_saml/js to override the view where the login form appear in order to print an URL to my SAML login.

In the past it worked, but now something changed on OwnCloud and now this js code is not loaded until the user tries to log with some credentials.
Seems like the app modules aren't loaded in the main view that shows the login form until the user have interacted with the system.



Is there an easy solution?   I have not idea about how the new version of OwnCloud works and sure that someone can help me to fix the user_saml app.

Solutions:

Ok I found that in order to load the app at the begginning, It is required to set the app as 'prelogin''s type
(At appinfo/info.xml   put on the '' value,  then the app will be loaded at the beginning).



Also I made a workarround to fix the problem that I'm not allowed to load apps/user_saml/auth.php

I load ?app=user_saml

And in the appinfo/app.php  I check if exists a $_GET['app'] = 'user_saml' and them execute the logic of the auth.php



But I'm still waiting for a solution of how enable views directly loaded at the browser.

Facing up to Facebook: Retrieving information

It is easy to post information  to Facebook.com but retrieving information is difficult and complicated. To me companies like Facebook, Apple and Microsoft do nothing without having an agenda. Facebooks agenda is of course getting the user to place content. Regardless of what Zuckerberg says about wanting to improve the world through social media the bottom line is the bottom line. There is no free lunch.

Previously I blogged about how I don't believe that companies should put their whole website and businees inside of a Facebook shell. Now that I have said this I going to show code. Because it's easy to talk about the why's-and-why-not's but showing them is better. The other day I got an interview task to embed a Facebook Page timeline to a website using the more customizable Open Graph API tools. Surprisingly I found the task was time consuming given the fact that Facebooks API docs and examples for PHP (or any programming language) are weak and almost non-existent.

Step by step

Setup your site as a Facebook application by logging in and surfing to developers.facebook.com and clicking on the Apps link in the top bar. I won't touch on this here because there is a good tutorial on Facebook and other parts of the web.

Download and setup the Facebook PHP-SDK:

require 'facebook/src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => 'App id Here',
  'secret' => 'App secret here',
));

$access_token = 'App access token here';

Get an access token:
https://graph.facebook.com/oauth/access_token?client_id=[]&client_secret=[]&grant_type=client_credentials

Use PHP curl:
$c = curl_init("https://graph.facebook.com/berlinto/feed?access_token=" .$access_token . "&limit=100");

 // necessary so CURL doesn't dump the results on your page
 curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);

 $result = curl_exec($c);
 curl_close ($c);

 $facebook_info = json_decode($result, true);
 print '<pre>';
 print_r($facebook_info);
 print '</pre>

The results:

Array
(
    [0] => Array
        (
            [id] => 116499591832278_116561445159426
            [from] => Array
                (
                    [name] => Carl Adam McDade
                    [id] => 100000381424682
                )

            [to] => Array
                (
                    [data] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Berlinto
                                    [category] => Website
                                    [id] => 116499591832278
                                )

                        )

                )

            [message] => Welcome to the Berlinto Facebook Page for PHPer's
            [type] => status
            [created_time] => 2012-09-06T15:20:56+0000
            [updated_time] => 2012-09-06T15:20:56+0000
            [comments] => Array
                (
                    [count] => 0
                )

        )

    [1] => Array
        (
            [id] => 116499591832278_116499601832277
            [from] => Array
                (
                    [name] => Berlinto
                    [category] => Website
                    [id] => 116499591832278
                )

            [story] => Berlinto joined Facebook.
            [story_tags] => Array
                (
                    [0] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 116499591832278
                                    [name] => Berlinto
                                    [offset] => 0
                                    [length] => 8
                                    [type] => page
                                )

                        )

                )

            [type] => status
            [application] => Array
                (
                    [name] => Reviews
                    [id] => 6261817190
                )

            [created_time] => 2012-09-06T11:38:59+0000
            [updated_time] => 2012-09-06T11:38:59+0000
            [comments] => Array
                (
                    [count] => 0
                )

        )

)

Explainations

As you can see there are a few things to know beforehand that are not readily apparent when reading the documentation. One is the fact that when you create an application you get the application id and the secret key but there is no access token provided. Again this is done on purpose. I find it hard to believe otherwise. For your cut and paste convenience I put up the URL here.  There is a "get access token" tools in the GraphAPI Explorer but you have to log in as the page user to get things correct. It would be easier if FB just made the tool available in the App settings area.

When you get the object back from the API call it comes in JSON format and when converted to a PHP array you will notice that "story" and "message" are not separated. So you will have code in some logic to your loop when gathering information from the array.

Facebook never uses the word REST  for the API. They assume you and I know what type of web service is provided by looking at the URL's which is quite frankly stupid. This because I get confused by the FQL which to me means SOAP when I see it. This is a documentation weakness where Facebook really could shine if they were interested.

PHP cURL is used here because for the life of me I could not get the built in API call to work. I then later found that using Curl is not only faster but recommended. This should have been in the documentation also.

Security

Lastly there is a security flaw in Facebooks implementation of the API or possibly a documentation error.
App Access Tokens should only be used when the posting functions are originated directly from your servers in order to keep them private to the app. For example, you should not publish using an App Access Token from within a native mobile app. Doing that could allow the user to obtain the App Access Token, which could then allow them to take actions on behalf of your app.
The problem here is that when the JSON is returned it contains paging URL's which show the app access token quite clearly. So if you want to page through the results there is an instant whole in security. So be careful about what keys you use when presenting the array information.

Facing up to Facebook

When I write about Facebook I am happy that I did not start my career as a programmer. My studies in economics gives me more insight to the hype. What I am going to do now is talk about why companies should not put all their programming into the Facebook basket.

Just recently I freelanced in two Drupal projects for German based companies. Both of them have only a facing page on their own URL and the rest of their online presence is via Facebook. One of them is not online yet but it is a dating site that is moving from a complete website to a Facebook only app. I can't say the name until release but that is happening soon. The other is a messaging service called Zoobe. Zoobe is a good idea and fun to use. But Zoobe only resides in the Facebook environment. I immediately questioned this decision because for me marketing a business or an application is about using every avenue available.

Facebook represents over thirty percent of internet traffic in reference URL's. This sounds like a lot but the reality is most of that traffic is only Facebooks. There is very little going into Facebook applications and even less for those applications not using FB advertising. Probably most if not all of Facebook traffic is relegated to online social games and shared images.

 In todays internet somethings are still very important to online business success. As a matter of fact you could say they are necessities. SEO is what most businesses struggle with daily. Think about how much potential traffic is lost in the layers of Facebook URL's, competition with other applications and the limitations placed by Facebook privacy and security. Yeah, doing only Facebook pretty much throws a good percentage of the internet out the window along with all the newer technologies that may come.

The greatest risk for Facebook only companies comes from Facebook. What happens when an application gets over shadowed by a Facebook "feature" (Zuckerberg has said no to FB apps but features are something else).  The Facebook IPO is seriously overpriced and the result of this will be a push to invent and establish products that may be in competition with third-party apps. If an app is of those "niche" business ideas then that niche would implode in a blink of an eye. User's  notorious for brand name recognition and putting the Facebook stamp on anything will mean they will jump from the third-party app to the safety of Facebook like rats on sinking ship.

 There are limits to what can be accomplished in the Facebook bubble. This is demonstrated by Zynga's move to establish their own platforms and websites outside of Facebook. As a hobby or an extra kick to business opportunities Facebook is great. But Facebook is not a perfect place for a growing business. It has limitations in technology and cannot promote the forward movement of other technologies. Consider this, a baby is happy to be in the comfort of the mother body. For nine months it prospers and grows. But what happens if it never leaves the security and space of the mothers womb?

Build a Drupal style hook system using PHP reflection

The Movico module is a scaffold for building Drupal modules in OOP and MVC. One requirement of the project is a hooking system, similar to Drupals, that uses OOP. The following is how I plan to build such a system using the PHP 5 reflection API.

This code shows how using Reflection makes it easy to create a system that hooks into several Class methods to build a linked menu. This moves two systems that are heavy resource users and overly cached from Drupal and places them into the Movico domain.

To try this out you can download and install the Movico module, place this code in ...movico/_controllers/hooks.class.inc. Then surf to ?q=app/hooks/get_hooks. If you get a access denied page then add this to the mvc.module

Update: Moving to hiveminds.Wordpress.com to get syntaxhighlighting and Linkedin connectivity


function mvc_access($uri){

$authorize = array(
'hello' => array('access foo'),
'hello_log' => array('access baz'),
'hello_log_view' => array('access foo','access baz'),
'get_hooks' => array('access foo','access baz'),
);



...movico/_controllers/hooks.class.inc
======================================



/**
* Normally the Classes would be in individual files and loaded via an iterator
*
*
* @author Carl McDade
* @since 2010-02-18
*/
class ConClass1 {

function hook_output()
{
$var[1] = 'link text(1)';
$var[11] = 'link text(11)';

return $var;
}
}

class ConClass2 {

function hook_output()
{
$var[2] = 'link text(2)';

return $var;
}
}

class ConClass3 {

function hook_output()
{
$var[3] = 'link text(3)';
$var[4] = 'link text(4)';

return $var;
}
}

class hooks{

public $hook = 'hook_output';
public $arr = array();

function _modules()
{
$vars = array('ConClass1','ConClass2','ConClass3');

return $vars;
}

function get_hooks()
{
foreach ($this->_modules() as $module)
{
$Class = new ReflectionClass($module);
$Method = new ReflectionMethod($Class->getName(), $this->hook);

if ($Method->isStatic())
{
$output = $Method->invoke(NULL);
}
else{

$instance = $Class->newInstance();
$this->arr = array_merge($this->arr, $Method->invoke($instance));
}
}

return mvc_view('default', $variables, implode('',$this->arr));
}
}

?>