WebConsults.EUQuicksearchKategorien |
Friday, October 28. 2011Reset Jenkins Continious Integration Server Password
If you need to reset the password of a Jenkins Continious Integration server.
Stop Jenkins:
usually /etc/init.d/jenkins stop
edit the config.xml
usually: /var/lib/jenkins/config.xml
Replace
Tuesday, August 9. 2011KISS: Zend_Captcha_Image in action
I just had to build in a Captcha to a simple form on a small side, i thought of using the Zend_Captcha_ReCaptcha but also saw some disadvantages.
- Re Captcha is the most common used captcha, if anybody will build a universal spam bot, ReCaptcha might be first target to implement.
- Re Captcha depends on a service so if you implement it your site will also depend on this service
Implementing a Zend_Captcha_Image is pretty simple, it is not looking as nice as Re Captcha but also works.
here is the code.
$captchaImgDir = 'path/to/were/images/will/be/written'; $captcha = 'path/to/trueTypeFontFile.ttf'; $this->addElement(new Zend_Form_Element_Captcha('captcha', array( 'captcha' => array( 'captcha' => 'Image', 'height' => '40', 'font' => $captchaFont, 'imgDir' =>$captchaImgDir, 'wordLen' => 3, 'timeout' => 300, ), ))); <?=$this->formLabel('captcha', 'Security Code')?><br /> <?=$this->form->getElement('captcha')->render() ;?><br /> KISS: Time to KISS
As i did not post anything for one year cause of to less time for really good posts and always wanted to write better quality articles, i know decided to write some KISS articles. In these articles i will post some usefull small things wich might not always be high level enterprise but giving some good ideas.
Shortnote: Disable all Form Fields Zend_Form
It is possible to disable all form fields using Zend Framework Zend_Form class.
maybe if the form is already send and you wanna display the data again inside form for optical reasons.
$form = new My_Zend_Form_Class(); foreach ($form->getElements() as $element) { $element->setAttrib('disabled', true); $element->setAttrib('readonly',true); } Monday, March 29. 2010PHP 5 Reflection access privat methods
There were highly idiologic discussions about if you should test your privates or not with unit testing or not,
in my opinion especially during Development with private methods performing for example calculations it could be useful to Unit Test these.
At least during development you make sure that these functions already work, and finally it´s better to change accessibility than just to set accessibility lower to make testing possible. Before PHP 5.3.2 it was not possible to change the accessibility but with the new ReflectionMethod it is.
But this feature needs to be used with care, it´s made for unit testing and maybe very special other cases wich are not in my mind yet.
Using some magic reflection stuff always makes code very hard to read, maybe you think it´s fance but others might get confused a lot.
Using the ReflectionMethod introduced in PHP 5.3.2 ReflectionMethod::SetAccesible ReflectionMethod Class PHP Unit Developer Sebastian Bergmann wrote an article about Testing Your Privates Sebastians Bergmanns Example: <?php class FooTest extends PHPUnit_Framework_TestCase { public function testPrivateMethod() { $method = new ReflectionMethod( 'Foo', 'doSomethingPrivate' ); $method->setAccessible(TRUE); $this->assertEquals( 'blah', $method->invoke(new Foo) ); } } ?> Tuesday, March 23. 2010Fake Zend Framework isXmlHttpRequest for Unit Testing
To manipulate the result Zend_Controller_Request_Http::isXmlHttpRequest()
maybe for testing XML Controllers in PHP Unit you just need to set the HTTP_X_REQUESTED_WITH value to XMLHttpRequest
Zend_Controller_Request_Http::isXmlHttpRequest() does nothing more than checking for this.
$_SERVER['HTTP_X_REQUESTED_WITH']="XMLHttpRequest"; public function isXmlHttpRequest() { return ($this->getHeader('X_REQUESTED_WITH') == 'XMLHttpRequest'); } public function getHeader($header) { ........ $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header)); if (!empty($_SERVER[$temp])) { return $_SERVER[$temp]; } Monday, February 8. 2010Remove Duplicated Entries from MySQL Table
This is a short tutorial how to remove duplicated entries from MySQL DB Table
First idea was just to do a simple DELETE statement on a SubSelect
DELETE FROM user WHERE id IN (SELECT u2.id FROM user AS u1 JOIN user AS u2 ON u1.name=u2.name WHERE u1.id < u2.id) Error 1093 (ER_UPDATE_TABLE_USED) SQLSTATE = HY000 Message = "You can't specify target table 'x' for update in FROM clause" This error occurs in cases such as the following: UPDATE t1 SET column2 = (SELECT MAX(column1) FROM t1); You can use a subquery for assignment within an UPDATE statement because subqueries are legal in UPDATE and DELETE statements as well as in SELECT statements. However, you cannot use the same table (in this case, table t1) for both the subquery's FROM clause and the update target.I was searching for a solution without using temporary table but didn´t find one yet. CREATE TEMPORARY TABLE duplicated_temp(id INT) TYPE=HEAP; INSERT INTO duplicated_temp SELECT u2.id FROM ex_user AS u1 JOIN user AS u2 ON u1.name=u2.name WHERE u1.id < u2.id; DELETE FROM user WHERE id IN (SELECT id FROM duplicated_temp WHERE 1); DROP TABLE duplicated_temp; Dynamic Model for Zend Framework
I always liked some kind of auto generated model to access a database.
I liked it the way Symfony does or the Zend Framework Tool.
But anytime using a generator is also a bit of mess.
The actual Zend Framework quickstart example has a 3 files way of implementing a Model, a Model Class, Model Mapper Class and Model DB Table ClassFew,
so for one DB Table you always have to create 3 classes which look almost similar, most times you just copy and paste those, and change a few things.
So i decided to create an very flexible model class, where you just need to define the properties and nothing more getter and sette methods will be called by magic functions. Even it has export function to an array.
You don´t have to create anything but you can create your own functions for getter and setter methods which would override the default ones.
In later state it could be possible to add a filter configurable in the model, but for first step i would like to keep it as slim as possible.
class Dynmodel_Model { protected $_id; protected $_created; public function __construct(array $options = null) { if (is_array($options)) { $this->setOptions($options); } } // // Magic Call function // @param <type> $name // @param <type> $arguments //@return <type> // public function __call($name, $arguments){ if(substr($name,0,3)=="set"){ return $this->__set(substr($name,3),$arguments[0]); } if(substr($name,0,3)=="get"){ return $this->__get(substr($name,3)); } throw new Exception('Method '.$name.' not Supported'); } // // Magic Setter Class // @param <type> $name // @param <type> $value // public function __set($name, $value) { $method = 'set' . $name; $propertyName="_".lcfirst($name); if(method_exists($this, $method)){ method_exists($this, $method); }elseif (('mapper' == $name) || !property_exists($this, $propertyName)) { throw new Exception('Invalid Property '.$propertyName); }elseif(property_exists($this, $propertyName)){ $this->$propertyName=$value; } } // // Magic getter class // @param <type> $name // @return <type> // public function __get($name) { $method = 'get' . $name; $propertyName="_".lcfirst($name); if(method_exists($this, $method)){ return $this->$method(); }elseif (('mapper' == $name) || !property_exists($this, $propertyName)) { throw new Exception('Invalid Property '.$propertyName); }else{ return $this->$propertyName; } } public function setOptions(array $options) { $methods = get_class_methods($this); foreach ($options as $key => $value) { $method = 'set' . ucfirst($key); if (in_array($method, $methods)) { $this->$method($value); } } return $this; } // // Returning the Objects as Array // @return Array // public function toArray(){ $values=array(); foreach(get_object_vars($this) as $pkey => $pvalue){ if(substr($pkey,0,1)=="_"){ $arrkey=substr($pkey,1); $call="get".ucfirst(substr($arrkey,1)); //calling value through objects get function $values[$arrkey]=$this->$call(); } } return $values; } } Thursday, January 21. 2010Zend Framework PHP based SOAP Server with Java JAX-RPC client
This example shows how to create an Zend Framework based SOAP Server and connect to it by a Java Client. The process itself is really easy but some things ara a bit tricky for example at the status were i created it there were some problems if using WS style for the SOAP Server so i decided to use RPC style. The Server basically allows a user to logon by credentials and gives back a userstatus, the Java Client is connecting through this service and requesting the userstatus.
The Soap Server Class
<?php // orginal code has phpdoc compatible comments with slash star // // SoapUserServer Class // // @author // // // Description of SoapUserServer // // @author johny // class Example_SoapUserServer { // // // Returns Api Version // @return string getApiVersion // public function getApiVersion() { $apiVersion="0.9.3"; return $apiVersion; } // // getUser // Returns user Status for a given Username, Password combination // @param string $username // @param string $password // @return string getUserResponse // public function getUser($username, $password){ $adapter = new Example_AuthAdapter($username,$password); $userStatus=false; //retrive login $auth = Zend_Auth::getInstance(); $auth->authenticate($adapter); $acl = new Zend_Acl($auth); if (!$auth->hasIdentity()) { //user not valid $userStatus=false; }else{ //user okay //@todo dynamic membership types $membership=$auth->getIdentity()->getMembership(); if($membership && $membership->getMembershipTypeId()>=1){ $userStatus="premiummember"; }else{ $userStatus="normalmember"; } } if($userStatus!=false){ return $userStatus; }else{ return "wrong credentials"; } } } ?> <?php class SoapController extends Zend_Controller_Action { // // Zend Soap Server Action // Representing the soap Server /// public function serverAction(){ if(isset($_GET['wsdl'])) { $autodiscover = new Zend_Soap_AutoDiscover(); $autodiscover->setBindingStyle(array('style' => 'rpc')); $autodiscover->setClass('Example_SoapUserServer'); $autodiscover->handle(); exit; } // disabling WSDL cache cause we are still in Development ini_set("soap.wsdl_cache_enabled", "0"); $server = new SoapServer('http://example.com/soap/server?wsdl'); $server->setClass('Example_SoapUserServer'); $server->handle(); $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout->disableLayout(); } } ?> package eu.webconsults.myapp.userauth; import java.rmi.RemoteException; import myapp.userauth.Example_SoapUserServerPort_Stub; import myapp.userauth.Example_SoapUserServerService_Impl; // // User Authorization class using Soap Server // @author johny // public class UserAuth { String username = null; String password = null; String usertype = null; Boolean isAuthorized = false; Example_SoapUserServerPort_Stub stub; // // Authenticating remote // // @param username // @param password /// public UserAuth(String username, String password) { this.username = username; this.password=password; this.retrieveRemoteUserStatus(); } // // Retriving remote User Status from Stub // @return /// private String retrieveRemoteUserStatus(){ try{ this.usertype = this.getStub().getUser(this.username, this.password); if(!this.usertype.equals("wrong credentials")){ this.isAuthorized=true; }else{ this.isAuthorized=false; } } catch(RemoteException re){ System.out.println("Remote Exception"+re.getMessage()); } return this.usertype; } // // // @return // private Example_SoapUserServerPort_Stub getStub(){ if(this.stub == null){ this.stub=(Example_SoapUserServerPort_Stub) (new Example_SoapUserServerService_Impl().getExample_SoapUserServerPort()); } return this.stub; } // // Getting Username // @return // public String getUsername(){ return this.username; } // // Getting Password // @return // public String getPassword(){ return this.password; } // // Returning Usertype // @return // public String getUsertype(){ return this.usertype; } } Tuesday, December 29. 2009Osapi Session Storage
Using the OSAPI Open Social API, i noticed there is no session storage available by default,
so this is a very quick way to implement a PHP-Session Bages Storage
// Session Storage implements Openid Storage Inside PHP Session, //for me the easiest way to handle openId data // // Description of osapiSessionStorage // //@author John Behrens (john.behrens@webconsults.eu) // class osapiSessionStorage extends osapiStorage{ // // Retrieves the data for the given key, or false if they // key is unknown or expired // // @param String $key The key who's data to retrieve // @param int $expiration Experiration time in seconds // public function get($key, $expiration = false){ if(!isset($_SESSION['osapi'])){ return false; } if(isset($_SESSION['osapi'][$key])){ return $_SESSION['osapi'][$key]; }else{ return false; } } // //Store the key => $value set. The $value is serialized // by this function so can be of any type // //@param String $key Key of the data // @param Any-type $value the data // public function set($key, $value){ $_SESSION['osapi'][$key]=$value; } // // Removes the key/data pair for the given $key // // @param String $key // public function delete($key){ unset($_SESSION['osapi'][$key]); } } ?> Thursday, October 22. 2009One more reason why Symfony **cks
I was working with
form_remote_tag() which is a usefull function if you create forms using AJAX request.
Simple usage is easy
Executes the URL Item Add and replaces content of the Element with item_list with it´s result.
Well what i would like to now is a Form which is permanent viewable and will reset itself if sended.
What i guessed
<?php echo form_remote_tag(array( 'update' => 'list', 'url' => 'entrys/create', 'complete' => "Form.reset('myForm')", 'id'=>'myForm' )); ?> <?php echo form_remote_tag(array( 'update' => 'list', 'url' => 'rntrys/create', 'complete' => "Form.reset('myForm')" ),"id='myForm' "); ?> Monday, October 12. 2009Tooltip Div with Jquery
Searching the web i found a lot of solutions and ToolTip Plugins wie z.b. Simpletip oder really simple tooltop, but after i had a short look at some i decided that they are all more or less usefull.
The most usuable entry i found was a short entry at Stackoverflow telling me anything i need to know.
My basic requirement was, Javascript code has to be Seperated from the design and the Webpage content.
So my php template looks like this
<? foreach($entrys as $entry): ?> <div id="entrylink_<?=$entry->id?>"> <a href="<?=$entry->link?>" onMouseOver="showEntryPreview('<?=$entry->id?>')" onMouseOut="hideEntryPreview('<?=$entry->id?>')"><?=$entry->name?></a> </div> <div id="entryinfo_<?=$entry->id?>" class="entry_preview"> ... some more information .... </div> <?enforeach;?> .entry_preview{ position:absolute; z-index:999; left:-9999px; background-color:#FF0000; padding:5px; border:1px solid #fff; width:250px; function showUserInfo(entryId){ var divOverlay=$('#entrylink_'+entryId); var divParent=$('#entryinfo_'+entryId); var parentPosition=divParent.position(); var parentWidth=divParent.width(); var parentHeight=divParent.height(); divOverlay.css('left', parentPosition.left+parentWidth); divOverlay.css('top', parentPosition.top+parentHeight); divOverlay.css('visibility', 'visible'); } function hideUserInfo(entryId){ $('#entryinfo_'+userId).css('visibility', 'hidden'); } Sunday, August 2. 2009Sending and Rendering Emails with Zend Framework
It took me a little while to figure out to solve a standard problem like sending an template or view script as email, the main problem is the original documentation doesn´t show anything about it, just sending email with text from a string, and if you search on the web, you find mostly the same thing or solutions which were not satisfying me.
//Rendering mail template to string $mail_view = new Zend_View(); $mail_view = new Zend_View(); /<strong> </strong> This will only work inside the MVC vontroller and <strong> handle over script path to the email view renderer </strong>/ $mail_view->addScriptPath($this->view->getScriptPaths()); $strMailBody=$mail_view->render('controllername/mail.phtml'); //configuring email $email_recipient_mail="recipient@example.com"; $email_recipient_name="Recipient Name"; $email_subject="Subject for the Email"; $email_sender_email="sender@example.com"; $email_sender_name="Sender Name"; //sending email with Zend_Mail() $mail = new Zend_Mail (); $mail->setFrom ($email_sender_email, $email_sender_email); $mail->addTo ($email_recipient_mail, $email_recipient_name); $mail->setSubject($email_subject); $mail->setBodyText($strMailBody); $mail->send (); Thursday, July 30. 2009Internationalization in User Generated Enviorments
User generated content in multilingual enviorments brings up new internationalizations problems,
in a social network or other enviorment with a lot of User Generated content, I18N could not be sticked strictly to the user, and even a content or discussion could be spreaden through different languages.
On usual websites a language is assigned to the frontend user, also on Youtube where it causes some problems.
I always recieve Mails like
Komentarze do filmu „>videoname<” Comentario sobre ">videoname<" publicado Reactie van >userwhopostedcomment< op ,>videoname<' Nouveau commentaire sur ">videoname<" Kommentar zu ">videoname<" gepostet" gepostetWhich all mean your video ... has been commented by ..., but it´s alsways in the default language to the commentor, no matter what my language is and no matter which language the comment is Written in. Comments itself are mostly written in english or the language the video is in. A solution could be to send it just in the recipient´s default language instead the actual frontend language, it would just make it easier for the recipient. Jeroen - Moie Video, echt Leuk Tommy - Why are all the Comments in Dutch Franz - Die Holländer finden ihre Sprache so Toll Antje - Ihre Sprache ist auch Supertoll Joost - Duits is alleen voor Moffen Tommy - In English Please Joost - German is for Kauts Only Franz - Geh doch Käse essen du KaaskoppAs you see users could communicate through different Languages, and maybe they even like it and switch Languages during a conversation, if you wanna run your site with an international flavour this is acceptable. Language Detection Language Detection could be usefull, to translate auto detection for example, but you could also hide content with Language Detection For Example: I got a Guestbook entry on my Dutch Netlog, somebody commentet the guestbook in German with something like "Hi ich habe ein bischen Deutsch gelernt, Wie geht es dir? viele grüsse". This entry were hidden cause it weren´t written in my actual frontend Language (Dutch), but actually i had choosen German as native language in my profile. So if you use something like Language Detection to hide content from foreign Languages, you must consider a user could be able to understand more than one language. Hiding content from the user is mostly a bad decission, cause even if the user is not able to read information might be usefull. The better way is always to sign the entry as an entry with different language and offer automated translation possibility. Where it could make sense to hide content is if a user is doing a general search on contents, at least in order of the search results. Friday, June 26. 2009Zend Debug Logger
http://extraordinaire.me/web-development/bootstrap-zend-framework/
(Page 1 of 3, totaling 38 entries)
» next page
|