Tag: kranthi

Motion And Animation: A New Mobile UX Design Material


  

Growing up, weekends were about worship in the Hinman household. Sunday mornings were reserved for a laborious worship ritual dictated by my parents. It required dressing up in uncomfortable clothes, going to church and pretending to listen to long-winded sermons about Jesus (while I drew doodles in the hymnals).

Saturday, however, was reserved as my day of worship, and I was a proud and dedicated disciple of the church of Saturday Morning Cartoons. Every Saturday, rain or shine, healthy or sick, I’d jump out of bed, run downstairs to the living room, plant myself in front of the TV, and celebrate the gospel of Wonder Woman, Captain Caveman, Scooby Doo and Papa Smurf for hours on end. While my parents were far from enthusiastic about my choice of religion, they tolerated it as a form of quid pro quo for Sunday church attendance.

Little did either of us know that those hours of fanatical dedication to the gospel of Saturday morning cartoon programming would eventually turn into a valuable vocational asset. I imagine that many of you reading this are members of the very same congregation — the group of us who recognize the subtle yet important religious differences between still-frame cartoons (like those found in the funnies section of the Sunday newspaper) and the animated TV cartoons before, which we gladly took the communion of orange juice and cereal every Saturday morning. We are the ones who understand what adding movement to something flat and lifeless can do. Movement breathes life into everything it touches.

Wonder Woman

Scooby Doo
Animated cartoons such as Wonder Woman, Scooby Doo and Captain Caveman taught me how movement can breathe life into drawings.

Adding movement to anything — whether a series of drawings or the transitions between the screens in a digital experience — is not just as easy as “adding water.” It’s an art that requires patience, an eye for subtlety and careful study of how objects and people move through space and time.

Transitions and subtle motion-based animations are emerging as a new and compelling mobile design material, worthy of being learned and being used with efficiency and grace. The addition of movement to a mobile experience can provide clarity, information about context and, frankly, a dash of joy and fun. However, too much animation or funky transitions can destroy a perfectly good mobile experience. This makes understanding the guiding principles behind the art of animation the best first step to artfully applying motion to your design work.

The people who understand this better than anyone are the legions of brilliant animators who have worked at Walt Disney. Thankfully for us, two animators by the names of Ollie Johnston and Frank Thomas decided to put pen to paper and share with the world the basic animation principles used by Disney animators during the filmmaking process in their book, The Illusion of Life: Disney Animation.

You may wonder what animation has to do with the mobile user experience. While the art form of animation was once the provenance of animated films and television, it has found its way into the computer and digital user experience realms. Artful animation has all but invaded the mobile user experience field. Whether it is the transitions between screens of a mobile experience or the behaviors applied to UI elements that can be interacted with using gestures, motion has become a significant mobile design element. It’s a design material you can use to help guide users through the mobile experiences you create.

Taking cues from Johnston and Thomas, this chapter explains the 12 basic principles of animation, borrowed from their 1981 book The Illusion of Life: Disney Animation. Although originally developed for animated film and television, these principles are completely applicable to screened-based experiences, too. If applied with subtlety and finesse, motion can elevate your mobile work, giving it that little touch of magic that you experienced every Saturday morning as a child.

The Illusion Of Life Disney Animation
The Illusion of Life: Disney Animation, by Frank Thomas and Ollie Johnston, outlines 12 basic principles of animation.

Here are the 12 basic principles of animation:

  1. Squash and stretch
  2. Anticipation
  3. Staging
  4. Straight ahead and pose-to-pose
  5. Follow through and overlapping action
  6. Slow in and out
  7. Arcs
  8. Secondary action
  9. Timing
  10. Exaggeration
  11. Solid Drawing
  12. Appeal

The 12 Principles Of Animation

Principle 1: Squash and Stretch

People and objects have an inherent mass. When an object moves, the quality of the movement often indicates the rigidity of the object. Manmade real-world objects, such as a bookshelf or wooden chair, are rigid and have little flexibility. Soft surfaces, such as clothing, organic objects and plant leaves, have less rigidity and higher flexibility. Squash and stretch is the animation principle used to accurately express the rigidity of an object.

Squash And Stretch
Organic and soft-surface objects, such as a balloon full of water, have some level of flexibility in their shape. Squash and stretch is the animation principle that helps depict this quality in animation.

Consider using this principle when you decide what feeling you want your mobile experience to evoke as users engage with it. Is your mobile experience a world of solid planes, rigid surfaces and sharp, exact movements? Or is it a world that’s more organic, with softer, pliable surfaces and easy, graceful movements? Squash and stretch can help you express those movements.

Flipboard

Apple's iBook
Screen transitions on Flipboard exhibit the principle of squash and stretch to express that the surfaces inside the world of the application are rigid and board-like. By contrast, the screen transitions in Apple’s iBook use the principle of squash and stretch to echo the flexible and organic movement of turning the pages of a real paper book.

Principle 2: Anticipation

When an illustrator depicts a moving object or character, three distinct phases should be considered to make the object’s movement realistic:

  • The preparation for the action,
  • The action itself,
  • The results of the movement.

Whether it’s a baseball batter winding up before a swing or the recoil of a spring before it’s sprung, anticipation is the animation principle used to prepare an object for movement. Anticipation is about orchestrating the components of a scene — lighting, composition or even the form of an object or character — in order to give the viewer a clue of what is about to happen.

Bowler
The crouch of a bowler, winding up before swinging a bowling ball, is an example of a pose and motion that the principle of anticipation captures.

Similar to its application in animated film and cartoons, when applied to the realm of mobile UX, anticipation is all about giving the user insight into what is about to happen next. For example, the principle could be applied to the visual treatment of the interface as the user opens an application. It could also be applied to the transitions between experiences. Because gesture languages are relatively new to users, the principle of anticipation could also be used to provide affordance for gestural UIs. Anticipation gives clues about the speed and direction that objects in a UI can move and the gestural possibilities of those objects.

Aperture Animation
The aperture animation found in the camera application of many smartphones prepares the user for the action of taking a photograph.

Palm Pre
The way the cards in the Palm Pre’s UI move is an affordance for users, giving them insight into the gestural language of the UI.

Window Shade Animation
The window shade animation on the home screen of the Windows Phone 7 employs the principle of anticipation by giving users a peek into the phone’s dynamic tiled UI.

Principle 3: Staging

People keen on selling property often “stage” a home, meaning they arrange each room in such a way that its purpose is completely clear. The principle of staging in animation is similar, because good staging makes the central idea of an animation completely clear to the viewer. In the world of mobile user experience, the principle of staging is most relevant when considering the transitions between screens and interactions. An interaction that is well staged combines light, color, composition and motion to direct the user’s eye to exactly where it needs to be as they interact with the experience. Well-staged mobile experiences have a sense of flow and ease, whereas poorly staged ones feel disjointed.

Staging
The well-staged illustration on the right makes the central idea — of two characters engaged in conversation — completely clear. The poorly staged illustration on the left leaves the dynamic between the two characters open to interpretation, making the central idea unclear.

Staging is a subtle yet important consideration when applying animation and motion to a mobile experience. A key challenge in creating natural user interfaces is that they lack a strong conceptual anchor. As a result, users who are new to natural UIs often feel anchorless as they navigate touchscreen experiences. If you apply good, strong staging to the animation and transitions of your mobile experience, then users will likely feel more grounded when they interact with it.

Mobile UX Staging
Good staging used in the iPad version of Keynote enables users to see exactly where the file they are currently working on lives in the application’s file structure. This subtle use of staging makes the user feel grounded in the experience.

Principle 4: Straight-Ahead and Pose-to-Pose

Straight ahead and pose to pose are techniques related to the animation drawing process. In order to capture fast dynamic action with unusual movement, animators will use the straight-ahead technique and draw every single frame of an animation. The pose-to-pose drawing technique employs the use of keyframes (i.e. the important frames of a sequence) and in-betweens (i.e. the intermediate frames that express movement between the keyframes).

Straight Ahead
The illustration on top depicts the straight-ahead technique in which every single frame of an animation is rendered. The illustration on the bottom represents the keyframes that will be used in a pose-to-pose animation.

The vast majority of animations and transitions used in mobile experiences employ the pose-to-pose animation technique. Pose-to-pose usually suffices for transitions that are not overly complex and that can be described easily. If you’d like to incorporate unusual or dynamic movement in your experience that can’t be achieved using pose-to-pose, then you’ll likely need to incorporate the straight-ahead technique.

Plants Vs. Zombies
Popular games such as Plants vs. Zombies for the iPad employ pose-to-pose animation techniques.

Fruit Ninja
Games with more complex movement, as in the iPad game Fruit Ninja, use straight-ahead animation techniques to capture dynamic motion.

Principle 5: Follow-Through and Overlapping Action

Imagine a big dog with giant jowls shaking his head side to side. The dynamic movement of the flabby skin on his face as he shakes his head to and fro is an example of the fifth animation principle: follow-through and overlapping action. While anticipation has to do with the preparation of an action, follow-through involves the end of an action. Actions rarely come to a sudden and complete stop, but rather come to a gradual end. Follow-through captures how parts of an object (like the dog’s jowls) continue to move even after other parts of the object (like the dog’s head) have stopped moving.

Follow-through
Follow-through captures how different parts of an object move at different rates (such as a dog’s head moving at a different rate than its ears or jowls).

Now imagine that dog walking down a sidewalk with his owner. His entire body is moving, but the timing of his legs is different than the timing of his tail or head. Overlapping action is the animation principle that captures how parts of an object — such as the dog’s head, tail and legs — move at different rates. Capturing the movement, as well as the slight variations in timing and speed of these parts, makes the objects seem more natural. An action should never be brought to a complete stop before another action has begun. Overlap maintains a flow between self-contained phrases of action.

While UI elements of a mobile experience should work together to form a whole, follow-through and overlapping action can help you define and communicate the relationship between UI elements. Transitions and animations are a great way to express how elements of a UI interrelate.

Windows Mobile
The transitions to and from the dynamic tiles on a Windows phone employ the principle of overlapping action. The tiles do not travel as one unit, but rather each tile moves at a different rate.

Principle 6: Slow In and Out

Whether it’s a car peeling out from a dead stop or a sprinter bursting out of the blocks and making tracks in a race, objects need time to accelerate and slow down. The sixth animation principle, slow in and out, deals with the spacing required to accurately depict the inherent law of inertia that governs all objects and people.

Objects in the world need time to accelerate and slow down. A strategy to accurately depict this type of motion is to add more frames of the object near the beginning and end of the movement and fewer in the middle.

Inertia
Adding more frames of the object near the beginning and end of a movement and fewer frames in the middle creates the illusion of the effect of inertia.

This principle works for characters moving between two poses, such as sitting down and standing up, and for inanimate moving objects, such as a bouncing ball. While the experiences we create for mobile UX often live in another world — the world behind the glass of the mobile device — allowing some of the laws of physics to exist in that world will make those experiences more relatable to users. Whether it’s a subtle difference in timing in how a list of data scrolls or the animated transition that appears as an application opens, slow in and out will make the motion phrases of your experience flow in a way that feels natural to the user.

Scrolling List

Scrolling List
The principle of slow in and out is applied to the scroll of lists in many mobile UIs. More frames are at the beginning and end of the movement. This effect makes the UI appear as if it is governed by the laws of inertia.

iPhone Home Screen

iPhone Home Screen
More frames are at the beginning and end of the scrolling transition of the home screen on the iPhone, making the application icons feel as though they adhere to the laws of inertia.

Principle 7: Arcs

Objects don’t move through space randomly. Instead, they move along relatively predictable paths that are influenced by forces such as thrust, wind resistance and gravity. The outline of a sparkler on the Fourth of July or skid marks on the pavement from a braking car are rare physical traces of these paths; usually, an object’s trajectory is invisible.

Sparkler
An object’s trajectory is largely invisible, except on rare occasions, such as a lit sparkler whose glowing sparks trace its path.

While these paths are largely unseen by the human eye, patterns exist for trajectories based on whether the object is organic or mechanical. Objects that are mechanical, such as cars, bicycles and trains, tend to move along straight trajectories, whereas organic objects, such as plants, people and animals, tend to move along arched trajectories. The object you want to animate should reflect these characteristics for greater realism.

When integrating motion into a mobile experience, consider whether the object being animated should reflect organic or mechanical qualities. If the former, then the arc animation principle suggests that the object should move along an arched trajectory. If the latter, then the object would move along a straight path.

Fish And Water
Natural elements such as the fish and water in this iPhone application move along arched trajectories.

Interface Elements
Interface elements in the Android mobile platform tend to move along straight lines, giving the UI a mechanical feeling.

Principle 8: Secondary Action

Imagine a squirrel running across your lawn and then leaping into a tree. The movement of the squirrel’s legs (considered the primary action) would be animated to emphasize the animal’s light, nimble, spry gait. The agile, undulating movement of the squirrel’s tail (the secondary action) would be a separate and slightly different type of movement that supports the primary action.

Secondary Action
The primary action of this animation is the movement of the squirrel’s body and legs. The shape and character of the squirrel’s tail as it moves is the secondary action. Together, they make the animation feel more realistic.

The squirrel’s tail is an example of secondary action, which supports the primary action of an animation sequence without distracting from it. Secondary action is applied to reinforce the mood or enrich the main action of an animated scene. The key to secondary action is that it should emphasize, rather than draw attention from, the main action.

The transition that occurs when a user clicks on a URL in an email, activating the browser on an iPhone, is an example of secondary action. The primary action is the browser window swinging forward into view. The secondary action is the email application receding into the background. Both actions occur simultaneously, but the secondary action of the email application supports the primary action of the browser window.

Mobile UX Secondary Action
An example of secondary action applied to an animated transition between application windows.

Principle 9: Timing

In animation, as in life, timing is everything. The frustration and awkwardness we feel when objects, characters or life itself move too slow or too fast is a testament to the innate importance of timing. In the world of animation, timing refers to the number of drawings or frames of a given action, which translates to the speed of the action on film. Timing is an important technique to master because it helps define the physical characteristics of an object, such as weight, size and scale. It can also make objects appear to abide by the laws of physics — as seen, say, in the speed of an object when pushed.

In addition to expressing physical characteristics, timing helps communicate the emotional state, mood and personality of an object or character. For example, subtle adjustments in timing can communicate the physicality and mood of the focused and deliberate Wile E. Coyote as he feverishly chases the quick, good-natured Road Runner, who by contrast moves with ease.

Timing
Timing — the mere speed at which the Road Runner moves — expresses both the physicality of the character (weight, height and scale) and the mood of the chase between the Road Runner and Wile E. Coyote.

Whether it’s the speed at which a list scrolls or the pacing of a transition between screens in a mobile application, timing is subtle yet important to master. Timing, as it applies to the mobile UX, is an art that requires finesse and practice. Take the time to understand what is being communicated through the movement and speed of the interface elements in your design. Also, take time for experimentation and trial and error as you begin to work with animation.

iPad Photo App

iPad Photo App
The timing in the iPad’s photo application is akin to the quick shuffling of a deck of cards. It expresses lightness, buoyancy and hyper-realistic speed.

Principle 10: Exaggeration

The principle that I feel brings the most fun to the animation party is exaggeration. It’s the element that makes movement feel dynamic, alive and just plain fun — much like the iconic characters Ren and Stimpy.

Ren And Stimpy
Canadian animator John Kricfalusi masterfully used exaggeration in the Ren and Stimpy animated television series.

An animation without some level of exaggeration might look accurate, but will likely feel stiff and mechanical. Mastering this principle involves identifying the relevant design element, figuring out how that element moves, and then tweaking the shape, scale or composition of the element so that it reinforces the movement, while adding a layer of drama. Exaggeration does not necessarily mean extreme distortion.

The classic definition of exaggeration, employed by Disney, is to remain true to reality but to present a wilder form. When applying this principle to movement in a mobile experience, exercise a certain level of restraint. If a scene contains several elements, then the exaggeration of those elements should be balanced relative to each other, to avoid confusing or annoying the viewer.

Trampoline

iPad Transition

iPad Transition

iPad Transition
The transition between the home screen of the iPad and the opening of an application is exaggerated. It makes opening an application feel springy and fun, like bouncing on a trampoline.

Principles 11 and 12: Solid Drawing and Appeal

Of the 12 animation principles outlined by Johnston and Thomas, the last two — solid drawing and appeal — are the most specific to character animation. Thus, they have slightly less relevance to mobile UX. Solid drawing is about honoring the rules of three-dimensional space and giving objects and characters appropriate dimensionality through volume and weight. Solid drawing requires animators to understand the basics of three-dimensional shapes: anatomy, weight, balance, light and shadow.

Solid Drawing
Solid drawing emphasizes three-dimensional shapes, accurate anatomy and animation that has a sense of weight, balance, light and shadow.

The appeal of an animated character is similar to the charisma of a live actor. A character who is appealing is not necessarily sympathetic — because villains or monsters can also be appealing. The important thing is that the viewer feels the character is real and interesting.

Methods Of Conveying Motion In Your Work

While the 12 principles developed by Johnston and Thomas are helpful for providing a vocabulary for motion and giving a sense of what’s possible, the core question of how to integrate motion into a design remains. The first step is to be aware of motion as a design material. The next step is to begin to integrate motion into the design process. Here are three key places in the design process where you can begin working with the magic of motion:

  • sketching,
  • wireframing,
  • prototyping.

Sketching

The time to start thinking about motion is during the sketching phase of your design process. Similar to how the movement of an animated character expresses its personality, the movement of screens and interface elements are powerful ways to express the personality of the mobile experience you’re creating. Sketching ideas for transitions and movement phrases early on will help you think about the personality that you want your mobile experience to convey and how you can use motion to communicate it.

Sketching
This motion storyboard sketch for the “opening iTunes details� transition is done with basic sticky notes.

Wireframing

Wireframing is yet another phase in the design process to work out the motion you want to integrate into the mobile experience. Because wireframes often convey the flow of screens, transitions — i.e. the motion between screens — fit naturally into wireframe documents. Using images and illustrations, you can begin to draw out the movements you have in mind. Because wireframes are documents that communicate design ideas to both developers and stakeholders in an organization, simply including motion specifications in the document will make everyone aware of motion and get them talking about it.

Wireframe
This motion specification in a wireframe document relies on images and illustrations.

Prototyping

Sketching and wireframing motion are good first steps, but nothing beats the real thing. Using prototyping tools whose vocabulary includes motion is one of the most powerful ways to foster your own fluency with motion as a design medium. Tools such as presentation software (Keynote, PowerPoint, etc.) include motion in their vocabulary. Instead of sketching motion, create low-fidelity prototypes using this software, which will help you experiment with motion and communicate your animation ideas more accurately to the design team.

Keynotopia
Creating prototypes with software such as Keynotopia allows you to animate user interactions and transitions between screens, enabling you to experiment with your motion ideas using the real thing.

Tips For Applying Animation Principles To Your Mobile UX Project

  1. Exercise restraint.
    Few things are more annoying than a mobile experience with too much animation pizazz. While animation is fun and exciting, don’t over-apply it, otherwise you might turn a great experience into a train wreck. Instead, rely on subtlety and finesse to convey motion.
  2. Complementary principles
    Whether it’s a scene in an animated movie or the transitions between screens in a mobile experience, animation principles rarely exist in isolation. Rather, most effective animations are an orchestration of many principles applied together. As your animation skills grow, you’ll learn how to artfully combine these principles like great recipes.
  3. Animation in a supporting role
    In film, animation supports the story. The same is true for mobile UX. Animation should complement the mobile experience, not be the star. Make sure your animation supports the interactions in the experience and doesn’t detract or confuse.

Summary

Once reserved for cartoons and movies, motion is a new and powerful design material in the mobile UX landscape. In addition to bringing focus and clarity, it can add a bit of character and even magic to the experiences you create. While any new design material can be time-consuming to learn, getting up to speed on animation and motion will probably feel intuitive and not feel like a chore, and it will make all those hours of watching Saturday morning cartoons as a child seem like a wise investment.

To sum up:

  • Transitions and subtle motion-based animations are emerging as a new and compelling mobile design material that can add efficiency and grace. The addition of movement to a mobile experience can bring clarity, information about context and a dash of joy and fun.
  • Although originally developed for animated film and television, the 12 basic principles of animation from the 1981 book The Illusion of Life: Disney Animation apply to screen-based experiences, too. These principles are listed below.
    1. Squash and stretch
    2. Anticipation
    3. Staging
    4. Straight ahead and pose to pose
    5. Follow-through and overlapping action
    6. Slow in and out
    7. Arcs
    8. Secondary action
    9. Timing
    10. Exaggeration
    11. Solid drawing
    12. Appeal
  • Three key point in the design process where you can begin working with the magic of motion are sketching, wireframing and prototyping.

(al)


© Rachel Hinman for Smashing Magazine, 2012.


A Designer’s Plea: Why Should Web Design Be A Profession?


  

When one goes to the professional, one expects to invest in his expertise. This investment requires no great leap of faith, as it is supported by a trust acknowledged among the general populace and duly warranted by the traditions of the profession. The standards and practices of an individual professional in the fields of, say, law, medicine, or aviation seldom present any great challenge to their clients’ preconceptions. Strict standards and regimented practices are the baseline assumption for all involved. Moreover, the results of those relationships generally support the ideal.

Unless we’re referring to the design profession. In which case, you can discount all of that.

Design, by comparison to other professions, is an odd and disappointing institution. While design exists as a profession in name at one end of the institutional spectrum, it also exists as a commoditized technical service industry at the other. And this is not necessarily a bad thing; it’s a construct of the market. It’s appropriate only within a very narrow context and far narrower than is generally assumed. But as I’ll argue in detail later, both designers and the public benefit from this commodity service aspect to the industry.

The problem with this situation is that there is no definitive guide for potential clients, detailing the differences between the commodity designers/agencies and the professional designers/agencies. To make matters worse, many who claim to be design professionals lack any understanding of the term and, therefore, erroneously claim it. As a result, those paying for a designer’s expertise often don’t know whether they’re working with a professional or a nonprofessional until some matter of vital import in the midst of a project makes it abundantly clear. At that point, the entire community of designers either triumphs or fails in the eyes of some very important people: those who need our responsible expertise and have gone to the trouble to pay for it.

You see, the uncompromising standards of design professionalism are highly constraining, expensive, and sometimes even off putting. Yet for the sake of our reputations and our clients’ fortunes they are our industry’s most essential traits. Therefore, the constraints of professionalism must be embraced and the costs paid. I submit to you that the design profession is an imperative.

It's Rough for Web designer.
The lack of transparency regarding professional standards in the industry means that the entire Web design community is held responsible for the mistakes of individuals. Image source: Andrew Mager.

Many would disagree. I understand that for any of this to make sense or even matter to you, you’ve got to believe that design should be a profession. Moreover, you’ve got to know why it should so that you can substantiate your belief. But why hold with this belief? It begs the question: why can’t design simply be a technical service industry, free from the fussy standards and constraints peculiar to a profession? It so often does fine as just that! Why is it important that design be a profession?

My effort here will be to answer that important question in a compelling and convincing way. I believe that in order to understand the profession’s imperative and place, we must fully understand how nonprofessional services fit into our industry and, by the same token, understand the voids created by the inadequacies of that approach. I also believe that this examination must take into account the motivations behind factors that promote unprofessional ideas and practices. So to start, let’s look at the most familiar and most commonly encountered facet of the design industry: the nonprofessional world of technicians.

Design as Commodity Service Industry

The opposite of professional is not unprofessional, but rather technician.
– David Maister, True Professionalism

Designers and just about everyone who employs them are familiar with the concept of designer as technician or service provider. Need a graphic? Tell the designer what it should look like and he can bang it out for you. Need an image gallery on a web page that wasn’t made to accommodate it? Show the designer how it should work and she can make it happen. Need a newsletter head mast font that communicates authority? Call the designer and he’ll send you 5 new authoritative candidates from which you can pick your favorite.

Multitudes of bosses, supervisors, and would-be clients already know what they want; they just don’t have the technical ability to make it. Call the designer!

Employing designers as technical service providers is an attractive prospect because it’s relatively easy, quick, and inexpensive. It’s easy for the designers too. Nonprofessional production service is light on obligation, plentiful, and often profitable. Design as a technical service industry addresses a market need and in this respect it’s necessary and beneficial. One could build a business doing this sort of work exclusively, and many freelancers and even agencies do just that. So long as the project’s scope and process aren’t too complex and the object of the work not significantly critical to anyone’s success, nonprofessional technical service may just fit the bill.

Keep in mind, though, that one feature of technical service employment, in contrast to professional employment, is that the designer gets managed. Working in a technical service capacity means the designer is there to provide little more than technical service, according to the standards, instructions, or whims of the one employing him. Design technicians need to be kept on task, on time, and their work moderated to reflect fluctuating supervisor preferences or customer preferences—whichever carries more weight. As in, “WAIT, lemme see… Well, the circle needs to be a darker blue. And can we make it more of an oval? Great. That page is going live in 30 minutes. Just send the graphic off to Jan when you’re done and she’ll put it up.”

Design As Commodity
The non-professional designer can provide quick, cheap fixes necessary to fast-paced businesses. As a design technician they aren’t constrained by artistic integrity. Image source: Jason Hickey.

This plentiful, light-on-obligation technical-service work brings with it certain tradeoffs. Costs, to use professional parlance. These costs are paid almost entirely by the customers, as they get results that are fractional to what could be realized in a professional relationship. The designers in these instances function merely as enablers to those costs and maybe even get paid well in the exchange. But there are some costs for the designers, too. They must suffer the potential indignity of having much of their expertise ignored and discounted, for instance.

For many, the benefits outweigh these costs. One of the more popular benefits is liberation from professional standards and constraints. For example, as technical service workers, designers and agencies have the luxury of taking on customers rather than clients. One does not discriminate among customers; all are welcome. In the commodity-design service realm, designers are engaged for their technical skill rather than for their uncompromising standards, depth of understanding, or ethical scruples. Therefore, one need not have years of experience or a rock-hard backbone to meet the minimal project requirements, which seldom include more than technical expertise. Technical skills are comparatively easy to project and maintain. Uncompromising moral and ethical standards, not so much. Those professional traits tend to chafe against the customer’s authority and strong will anyway (the customer is always right) and could jeopardize customer satisfaction and designer income opportunities. By contrast, the “I can do whatever you want me to do” approach is often more attractive.

Perhaps the most common articulation of nonprofessional design is subcontracting. Many designers and even agencies devote the majority of their project work to employing or being employed as subcontractors. Sadly, most subcontracting arrangements are not just nonprofessional but highly unprofessional, as they are set up to circumvent designer authority and critical communication in a fog of dishonesty. However, as long as the project context accommodates expediency and requires no significant investment or obligation, nonprofessional subcontracting (and no, there’s no such thing as professional subcontracting) can bring relative ease and speed to a simple project.

Subcontracting also extends the liberation of commodity service to larger projects and can thus expand profit opportunities. The results are inevitably mediocre, but there can be no denying that economy and expediency often outweigh quality concerns. There is a large and thriving market for “good enough,” especially when it preserves a strong-willed customer as the decision maker or obviates uncomfortable complexity in a project.

This arrangement can work so long as the results need be no better than what the customer or subscontractee can conceive of and allow. In these instances the designers are not expert decision makers, but rather the idea presenters and technical tool operators. Many designers are quite happy in this limited and comparatively safe capacity. Sometimes (most times?), however, clients need or are looking for something more dependable and more substantial than commodity design service. Professionalism is hard and many of its constraints present hurdles too great for designers to consider. But while designers typically balk at its constraints and obligations, the idea of professionalism is certainly attractive.

The Idea of Professionalism in Design

Without question, designers of all stripes love the idea of professionalism. It’s just that most prefer that idea remain as vague as possible in practical definition and application. The result is that the concept gets relegated to a station of subjectivity and cited merely for its halo effect.

I find that the vast majority of designers, when asked to define it, associate professional design practice almost exclusively with technical quality or “seriousness,” ignoring the uncompromising ethical, process, discrimination, and accountability factors. This is an unfortunate and disappointing sentiment, as professionalism has absolutely nothing to do with technical quality; which should merely be one positive result of projects involving professionals.

The reason for this preference is not so deep or difficult to understand: professionalism is expensive for designers. Proper preparation takes years and requires institutional guidance from senior professional peers. Professional standards impose grave responsibilities on the designer and are difficult to uncompromisingly maintain. They also tend to challenge the preconceptions of just about everyone who encounters them; designers included. According to the character of those brushing up against them, requirements for the professional conduct of design projects can be refreshingly positive or intensely off-putting.

Design is craft
Design is craft, but no matter how skilled you are as a designer, unless you are equally prepared in professional matters, your prospects will be limited and your circumstances compromised. Image source.

The refreshingly positive part is easy enough to understand. The off-putting part is due to the fact that few people inside or outside the industry expect designers to employ discrimination or to eliminate compromise with regard to moral, ethical, business, or process standards. Most potential clients and most designers believe that designers should simply behave as merchants; eagerly following whichever path the profit opportunity leads. Because unprofessional and nonprofessional employment has ever dominated our industry, most potential clients believe they should run their own project and make the design decisions after being presented with options. Most designers believe they should simply be told how high to jump and which hoops to jump through. Note: there exists no profession within those ideas.

As to expense, one unpopular result of maintaining professional standards is that a freelancer’s or agency’s viable client pool gets significantly reduced…which is nuts in the minds of most folks. Prevailing wisdom finds fault with any practice that deliberately limits opportunity for profit by applying what cultural convention perceives or defines as obtuse discrimination. Going along to get along makes far more sense. Why would anyone invite the difficulty of uncompromising standards into their life or their design practice? How does it even make sense that design should be a profession?

The Professional Imperative

When you think beyond the apparently easy money, cultivated expediency, and low-obligation assumed for some design projects, a couple of things beg for consideration:

  1. these qualities can ethically describe only the most insignificant of projects, and
  2. design results and the processes required for realizing them impact the experience and fortunes of real people.

People’s household incomes, staff payrolls, and economic futures often hinge upon how competent, how ethical, and how uncompromising their designers are.

These facts place a grave obligation on designers and on the industry itself. Every employment of a designer is an investment that demands a positive and profitable return. Designers have an obligation to meet that demand in prepared fashion. The fact is many projects—most, I’d argue—require understanding, skills, standards, and obligations beyond what is typically assumed. The commodity design service industry ignores this fact.

Uncompromising standards are the rule where quality and ethics matter, because these things are not bargaining chips. A designer’s comfort with or allowance for compromise has no place in a consequential design project. Since the commodity service approach is built on compromise and expediency, consequential projects can in no way be served by that segment of our industry. What’s more, common customer assumptions brought to commodity services are inappropriate in professionally run projects.

The ethical constraints for such projects do not allow for clients to compromise or circumvent the professional’s standards and prescriptions. This logical standard reflects the extension of the profession’s obligations into society and allows a design professional to demonstrate responsibility by not allowing the client to harm himself or others by deliberate choice and yet remain as a client. Despite how design organizations typically choose to define social obligation, it is established not on emotional or preferential grounds, but on moral and ethical grounds.

These moral and ethical grounds reflect practical mechanisms. For instance, clients need some acknowledged institutional assurance that their designer or agency will not abuse their relationship for financial advantage; that the fees paid and the work delivered amount to a mutually profitable exchange and not simple opportunism. They need the same reasonable assurance that their designer’s or agency’s work or process is not tainted by any conflict of interest. Moreover, clients need some acknowledge institutional assurance that their designer is worthy of the authority they’ve invested in him and that he is qualified to make the many crucial decisions in the project.

These qualities should be widely understood to be as associated with a specific segment of our industry; gathered up as the acknowledged professional qualities of members of the profession rather than happy exceptions that clients find by hit or miss. The term “design professional” should have an objective definition acknowledged by the public. Therefore, this segment of our industry must be devoted to a codified set of uncompromising standards. Design professionals should be identifiable to their client pool not because of how they lay claim subjectively to the term, professional, but by how they approach their dealings according to vital moral ideals and how they publicly proclaim adherence to an objective, ethical, social contract.

There is no Moral Compass App
Ethical responsibility is not a now-you-use-it now-you-don’t proposition. To secure the long-term trust of clients professionalism requires that standards be rigorously kept. Image source: Jason Tester.

To survive, these qualities must be cultivated in institutional fashion. Otherwise they reside only in individuals, locked up rather than compounded among peers over time. The profession and its culture are created in agencies and studios run by design professionals. It is not created in schools or universities, organizations, or magazines; despite what those merchants would otherwise proclaim.

As professionals, designers then have obligations to society, to their clients, to their peers, and to the profession itself. These obligations are imperative and they require a culture that respects, upholds, and reinforces them with a frequency and pattern not dependent on individual-member whim. Ultimately, professionals are defined by how they meet and uphold the fullness of these obligations in the conduct of their work, and by no other measure (as great design quality must be one’s baseline assumption).

Though this is not the primary thrust of my article, I’m compelled to suggest here that few are well served and a great many ill served by the existence of a design profession in name only. With the character and concept of “professional” so greatly varied throughout our industry, designers’ self-described professional efforts often undermine the ideal. Far too many potential clients have rightly developed a cynical view of the design profession. Designers of all sorts fight this view and sadly have to shape their approach and process to mitigate it. This is a failure, as our practices should not be shaped by cynicism.

This is what you get when truly professional practice is represented and perpetuated not by thriving, consistent culture inside agencies and studios as a rule, but by disparate examples that are often refuted by the most common case. So while an actual design profession exists, it doesn’t in any cultural sense in the industry. This must change if our profession is to have any articulate and objective meaning in society.

As I referenced at the start of this article, it requires no great leap of faith or perceived gamble for a client of a legal, surgical, or aviation professional to invest requisite trust and confer full contextual authority in their dealings. These investments are assumed and required if a professional is to cultivate a positive or successful outcome for his clients. The cultures and traditions of those professions facilitate that permission. The cultural tradition of design is inconsistent on this point and that must change if designers are to be widely allowed to deliver the fullness of their expertise.

Technical service in a commodity market can work and can produce positive results. Designers can find profit and many customers can find satisfaction there. I submit to you, though, that the design profession as a distinct and conspicuous segment of the design industry is not just a commercial imperative, but a cultural and moral imperative. Professional should be not some vague, inarticulate idea or an exclusive and elite qualification beyond the reach of the average designer. It should be an expected compulsory station for most designers, fueled and perpetuated by the mainstream culture of our industry.

Image source of picture on front page.

(al) (jc)


© Andy Rutledge for Smashing Magazine, 2012.


Powerful Command Line Tools For Developers


  

Life as a Web developer can be hard when things start going wrong. The problem could be in any number of places. Is there a problem with the request you’re sending, is the problem with the response, is there a problem with a request in a third party library you’re using, is an external API failing?

Good tools are invaluable in figuring out where problems lie, and can also help to prevent problems from occurring in the first place, or just help you to be more efficient in general. Command line tools are particularly useful because they lend themselves well to automation and scripting, where they can be combined and reused in all sorts of different ways. Here we cover six particularly powerful and versatile tools which can help make your life a little bit easier.


(Image credit: kolnikcollection)

Curl

Curl is a network transfer tool that’s very similar to Wget, the main difference being that by default Wget saves to a file, and curl outputs to the command line. This makes it really simple to see the contents of a website. Here, for example, we can get our current IP from the ifconfig.me website:

$ curl ifconfig.me
93.96.141.93

Curl’s -i (show headers) and -I (show only headers) options make it a great tool for debugging HTTP responses and finding out exactly what a server is sending to you:

$ curl -I news.ycombinator.com
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Cache-Control: private
Connection: close

The -L option is handy, and makes curl automatically follow redirects. Curl has support for HTTP Basic authentication, cookies, manually setting headers and much, much more.

Ngrep

For serious network packet analysis there’s Wireshark, with its thousands of settings, filters and configuration options. There’s also a command-line version, TShark. For simple tasks I find Wireshark can be overkill, so unless I need something more powerful, ngrep is my tool of choice. It allows you to do with network packets what grep does with files.

For Web traffic you almost always want the -W byline option, which preserves linebreaks, and -q is a useful argument which suppresses some additional output about non-matching packets. Here’s an example that captures all packets that contain GET or POST:

ngrep -q -W byline "^(GET|POST) .*"

You can also pass in additional packet filter options, such as limiting the matched packets to a certain host, IP or port. Here we filter all traffic going to or coming from Google, using port 80 and containing the term “search.”

ngrep -q -W byline "search" host www.google.com and port 80

Netcat

Netcat, or nc, is a self-described networking Swiss Army knife. It’s a very simple but also very powerful and versatile application that allows you to create arbitrary network connections. Here we see it being used as a port scanner:

$ nc -z example.com 20-100
Connection to example.com 22 port [tcp/ssh] succeeded!
Connection to example.com 80 port [tcp/http] succeeded!

In addition to creating arbitrary connections, Netcat can also listen for incoming connections. Here we use this feature of nc, combined with tar, to very quickly and efficiently copy files between servers. On the server, run:

$ nc -l 9090 | tar -xzf -

And on the client:

$ tar -czf dir/ | nc server 9090

We can use Netcat to expose any application over the network. Here we expose a shell over port 8080:

$ mkfifo backpipe
$ nc -l 8080  0<backpipe | /bin/bash > backpipe

We can now access the server from any client:

$ nc example.com 8080
uname -a
Linux li228-162 2.6.39.1-linode34 ##1 SMP Tue Jun 21 10:29:24 EDT 2011 i686 GNU/Linux

While the last two examples are slightly contrived (in reality you’d be more likely to use tools such as rsync to copy files and SSH to remotely access a server), they do show the power and flexibility of Netcat, and hint at all of the different things you can achieve by combining Netcat with other applications.

Sshuttle

Sshuttle allows you to securely tunnel your traffic via any server you have SSH access to. It’s extremely easy to set up and use, not requiring you to install any software on the server or change any local proxy settings.

By tunneling your traffic over SSH, you secure yourself against tools like Firesheep and dsniff when you’re on unsecured public Wi-Fi or other untrusted networks. All network communication, including DNS requests, can be sent via your SSH server:

$ sshuttle -r <server> --dns 0/0

If you provide the --daemon argument, sshuttle will run in the background as a daemon. Combined with some other options, you can make aliases to simply and quickly start and stop tunneling your traffic:

alias tunnel='sshuttle --D --pidfile=/tmp/sshuttle.pid -r <server> --dns 0/0'
alias stoptunnel='[[ -f /tmp/sshuttle.pid ]] && kill `cat /tmp/sshuttle.pid`'

You can also use sshuttle to get around the IP-based geolocation filters that are now used by many services, such as BBC’s iPlayer, which requires you to be in the UK, and Turntable, which requires you to be in the US. To do this, you’ll need access to a server in the target country. Amazon has a free tier of EC2 Micro instances that are available in many countries, or you can find a cheap virtual private server (VPS) in almost any country in the world.

In this scenario, rather than tunneling all of our traffic, we might want to send only traffic for the service we are targeting. Unfortunately, sshuttle only accepts IP address arguments and not hostnames, so we need to make use of dig to first resolve the hostname:

$ sshuttle -r <server> `dig +short <hostname>`

Siege

Siege is a HTTP benchmarking tool. In addition to load-testing features, it has a handy -g option that is very similar to curl’s -iL, except it also shows you the request headers. Here’s an example with Google (I’ve removed some headers for brevity):

$ siege -g www.google.com
GET / HTTP/1.1
Host: www.google.com
User-Agent: JoeDog/1.00 [en] (X11; I; Siege 2.70)
Connection: close

HTTP/1.1 302 Found
Location: http://www.google.co.uk/
Content-Type: text/html; charset=UTF-8
Server: gws
Content-Length: 221
Connection: close

GET / HTTP/1.1
Host: www.google.co.uk
User-Agent: JoeDog/1.00 [en] (X11; I; Siege 2.70)
Connection: close

HTTP/1.1 200 OK
Content-Type: text/html; charset=ISO-8859-1
X-XSS-Protection: 1; mode=block
Connection: close

What Siege is really great at is server load testing. Just like ab (an Apache HTTP server benchmarking tool), you can send a number of concurrent requests to a site, and see how it handles the traffic. With the following command, we’ll test Google with 20 concurrent connections for 30 seconds, and then get a nice report at the end:

$ siege -c20 www.google.co.uk -b -t30s
...
Lifting the server siege...      done.
Transactions:                    1400 hits
Availability:                 100.00 %
Elapsed time:                  29.22 secs
Data transferred:              13.32 MB
Response time:                  0.41 secs
Transaction rate:              47.91 trans/sec
Throughput:                     0.46 MB/sec
Concurrency:                   19.53
Successful transactions:        1400
Failed transactions:               0
Longest transaction:            4.08
Shortest transaction:           0.08

One of the most useful features of Siege is that it can take a file of URLs as an input, and then hit those URLs rather than just a single page. This is great for load testing, because you can replay real traffic against your site and see how it performs, rather than just hitting the same URL again and again. Here’s how you would use Siege to replay your Apache logs against another server to load test it:

$ cut -d ' ' -f7 /var/log/apache2/access.log > urls.txt
$ siege -c<concurrency rate> -b -f urls.txt

Mitmproxy

Mitmproxy is an SSL-capable, man-in-the-middle HTTP proxy that allows you to inspect both HTTP and HTTPS traffic, and rewrite requests on the fly. The application has been behind quite a few iOS application privacy scandals, including Path’s address book upload scandal. Its ability to rewrite requests on the fly has also been used to target iOS, including setting a fake high score in GameCenter.

Far from only being useful to see what mobile applications are sending over the wire or for faking high scores, mitmproxy can help out with a whole range of Web development tasks. For example, instead of constantly hitting F5 or clearing your cache to make sure you’re seeing the latest content, you can run

$ mitmproxy --anticache

which will automatically strip all cache-control headers and make sure you always get fresh content. Unfortunately it doesn’t automatically set up forwarding for you like sshuttle does, so after starting mitmproxy you still need to change your system-wide or browser-specific proxy settings.

Another extremely handy feature of mitmproxy is the ability to record and replay HTTP interactions. The official documentation gives an example of a wireless network login. The same technique can be used as a basic Web testing framework. For example, to confirm that your user signup flow works, you can start recording the session:

$ mitmdump -w user-signup

Then go through the user signup process, which at this point should work as expected. Stop recording the session with Ctrl + C. At any point we can then replay what was recorded and check for the 200 status code:

$ mitmdump -c user-signup | tail -n1 | grep 200 && echo "OK" || echo "FAIL"

If the signup flow gets broken at any point, we’ll see a FAIL message, rather than an OK. You could create a whole suite of these tests and run them regularly to make sure you get notified if you ever accidentally break anything on your site.

(cp)


© Ben Dowling for Smashing Magazine, 2012.


UX Meets Security: Better Password Masking For Sign-Up Forms


  

Masking passwords is an old practice that’s commonly implemented in sign-up and log-in forms. It’s used to prevent over-the-shoulder snoopers from catching the user’s password. While masking passwords is a good security practice, there’s a chance it could jeopardize the user experience of your sign-up form. When users sign up on a website, they expect a no-hassle, worry-free form to fill out. But masking the password could prevent that.

Good For Logging In, Bad For Signing Up

Log-in forms are used more often than sign-up forms. Users only need to sign up once to create an account, whereas they will need to log in multiple times to access their account. Because log-in forms are used so frequently, there’s a strong chance that users will end up typing their password in front of other people. Users sometimes want to show their friends or colleagues something on the website, and they would need to log in to do so. Therefore, masking passwords in log-in forms is good because it keeps passwords hidden every time the user logs in.

However, masking passwords in sign-up forms is different. Password masking generally causes users to make more typing errors because they can’t see what they’re typing and can’t tell whether they’ve made a mistake. The consequences of making a typing error when logging in are not as serious as making one when signing up. If the user fails to type in the right password when logging in, they simply try again. If they type in the wrong password when signing up, they’ll get locked out of their account when they try to log in and will have to reset their password. The user isn’t to blame when this happens. It’s the designer’s fault for not making it easy for the user to see what they’re typing in the password field.

What If We Omit Confirmation Fields In Sign-Up Forms?

A big hurdle that password masking creates for users is the password-confirmation field commonly found in sign-up forms. This field requires users to retype their password and checks that both match so that the wrong password doesn’t go through. The reason why password-confirmation fields exist is that users sometimes make typos when typing their password with masking on, and this extra field can catch those typos.

Password Confirmation Field

Password-confirmation fields might be well intentioned, but they have a downside. Users are prone to making even more typos because they have to type their password twice in separate fields with masking on. What’s worse is the extra work they have to do to correct their typos; because they can’t see where their typos are, users have to clear the fields entirely and retype their password. The password-confirmation field not only causes more typos, but forces users to do more work to fix them, thus slowing users down and making sign-ups more of a pain.

Unmasking Passwords Temporarily Decreases Typos

Masking passwords in sign-up forms might give users more trouble than it’s worth. It masks not only the password, but any typos the user makes, making them hard to spot and fix. The security it provides is often less than helpful because many people usually sign up for websites in private, with no one looking over their shoulder. Signing up is usually a one-time deal; once they’ve done it, they don’t need to do it again. Displaying their password in plain text that one time when they are alone is probably not as a significant security risk as we tend to think. The chance of a snooper catching the password is slim to none, even if the user is signing up in public, because most snoopers aren’t random strangers, but rather someone the user knows.

Typing Masked Passwords

The solution to all of these issues is to temporarily unmask the password so that the user can fill in the field quickly and accurately — i.e. unmasking the password for a moment so that the user can see what they’ve typed. Temporary unmasking decreases typos and makes it easy for users to catch and fix any typos they make. And the user doesn’t have to worry about snoopers stealing their password because the unmasking is quick, e.g. if we unmask a couple of last characters typed in. Snoopers would have to memorize a string of (hopefully) random alphanumeric characters in a matter of seconds, which is very hard to do. If we unmask only last characters, they would need to look over the shoulders for a longer period of time to be able to “catch” the whole pass phrase.

I strongly believe that a lot of the snooping paranoia is in our minds — the bigger issue is users getting locked out of their account because of typos caused by masked passwords. Below are a couple of simple techniques to prevent that from happening.

Unmasking on Field Focus

You can make the password field easy to fill in and secure at the same time by unmasking the password when the keyboard focus is on the field and then automatically masking it when the focus is off the field. This allows the user to see the characters they’re typing only when the password field is selected, thus decreasing the risk of typos and preventing others from sneaking a peek when the user has moved on to other fields.

Masking- Field Focus

Another small security measure you could add is to display the user’s password in small, light-gray italicized text. Thus, being able to make out each character would require moving close to the screen. In the unlikely event that a snooper is looking on, the modified text would make the password indiscernible to everyone except the person sitting right in front of the screen.

Another option would be to display only the last characters of the password while hiding other characters with asterisks, thus confirming the user’s input as the password is typed in.

Unmasking With a Checkbox

Another approach is to provide a checkbox for unmasking. Thus, when the user types their password, it is masked, but when they check the box, it gets unmasked, allowing them to see whether they’ve made a typo. A little more effort is required with this approach with the checking and unchecking, but it’s far better than a password-confirmation field because it enables users to see and fix their typos with ease.

Masking Checkbox

Balancing Security And User Experience

Following design conventions is generally advisable, but when a convention slows users down, complicates a task or increases the chance of error, it needs serious reconsideration. Security should be balanced with the user experience. Favor security too much over the experience and you’ll make the website a pain to use. Favor the experience too much over security and you’ll make visitors nervous about using the website. When you find that balance, users won’t have any trouble using your website, even if it doesn’t adhere to every design convention.

(al)


© Anthony T for Smashing Magazine, 2012.


Essentials: Utilizing User Roles In WordPress


  

Roles have been an integral part of WordPress for quite some time now — many functions associated with managing them have been in place since version 2.0.0. Despite this longevity, they are rarely utilized which is a shame since they allow for the easy setup of custom user types (and also have the ability to micro-manage them). In this article, you’ll learn everything you need to utilize user roles in WordPress and make the most of this incredible built-in functionality.


Large view.

Terminology

The main terms to know are “role” and “capability”. Capabilities are the core of the system, they represent the things you can do. An example of a capability is switch_themes. A user who has this capability is able to change the look of the website using the Appearances section in the admin. Those who do not have this capability will not be able to do so.

Roles are simply a named set of capabilities. Imagine you have capabilities like edit_post, add_user and so on. Instead of listing all 50 of them for each and every user who you’d like to be an admin, simply assign each user the “admin” role and then assign all the capabilities to that role.

The Default Setup

By default, WordPress has six roles and about 57 capabilities. Each role has a different combination of capabilities which endow the user with the appropriate rights and privileges.

For example, a contributor can edit and delete his own posts, but cannot control when these posts are published (and cannot delete those posts once they are published). This is because they have the edit_posts and delete_posts capabilities, but they do not have the publish_post and delete_published_post capabilities.

The default setup offered by WordPress is very well thought out and should not be modified, only added to. If it is changed, you could face difficult problems later on — like a contributor being able to remove posts from your website, or an admin not being able to change the theme.

When New Roles And Capabilities Are Needed

New roles usually come hand-in-hand with new capabilities. Usually, we first create a set of new capabilities, which are held by the admin (and a new role, as well). Let’s look at an example.

If you have a large website, chances are you have a marketing team. This team doesn’t need to be able to edit and publish posts, but they do need access to advertising stats, trending search topics, etc. Perhaps it would also be beneficial to allow them to manage categories and comments for SEO purposes and customer satisfaction, respectively.

Our first order of business is to look at the advertising stats and trending searches. This is not something WordPress offers by default, so let’s presume it has been built as a plugin. Let’s create a capability called view_stats. This will be given to the marketing people and of course to the admin. Other users — like editors and authors — do not need to see the stats (which, in many case, is sensitive data) so they will not receive this capability.

Our second task is to decide what other capabilities our marketing people need. Based on our assumptions above, they will need the read, manage_links, manage_categories and moderate_comments capabilities.

Lastly, we would use some coding chops to create a new role named “Marketing�, and assign the above-mentioned capabilities to it. Once that has been done, we are able to appoint the “Marketing� role to any user within the “Add User� and “Edit Profile� page.

Basic WordPress Functions

To manage roles and capabilities effectively, all you need is five very straightforward functions:

  • add_role() — Enables you to add a custom role
  • remove_role() — Enables you to remove a custom role
  • add_cap() — Enables you to add a custom capability to a role
  • remove_cap() — Enables you to remove a custom capability from a role
  • get_role() — Gets information about a role as well as associated capabilities

If you would like to view the documentation for these functions, you can take a look at the Roles and Capabilities section in the Codex.

Implementing New Roles And Capabilities

The full implementation of roles and capabilities requires more than just the five functions I mentioned. We’ll also need to use functions for checking capabilities, we’ll need features which are only available to certain roles, and so on.

Adding the Roles and Capabilities

$marketing = add_role( 'marketing', 'Marketing', array(
    'read' => true,
		'manage_links', 
    'manage_categories', 
    'moderate_comments',
    'view-stats'
));

$role = get_role( 'administrator' );
$role->add_cap( 'view-stats' );

The function above will add our new “Marketing” role. It adds four capabilities which are already included in WordPress and a fifth one which is a custom capability. As you can see, no special coding is required to add custom caps — just include them in the array when adding the role. Once we add the new role, we make sure to add our new capability to the admin role as well.

Note that the add_role() fuction returns a WP_Role object on success or NULL if the role already exists.

Since the above code will be used in a plugin, the best way to use it is to utilize hooks, and to add the capabilities to the administrator only when we first create the role.

add_action( 'admin_init', 'add_custom_role' );

function add_custom_role() {
    $marketing = add_role( 'marketing', 'Marketing', array(
        'read' => true,
	    	'manage_links', 
        'manage_categories', 
        'moderate_comments',
        'view-stats'
    ));

		if( null !== $marketing ) {
        $role = get_role( 'administrator' );
        $role->add_cap( 'view-stats' );
    }
}

Checking for Capabilities and Roles

Once we have our system in place we can check for capabilities and roles. This allows us to make sure that only users with the right capabilities can do certain things.


add_action('admin_menu', 'register_stats_Page');

function register_stats_Page() {
    add_menu_page( 'Marketing Info', 'Marketing Info', 'view_stats', 'marketing-info', 'show_marketing_info' );
}

function show_marketing_info(){
   if( ! current_user_can( 'view-stats' ) ) {
      die( 'You are not allowed to view this page' );
   }
   echo "

This is the marketing stats page

"; }

The code above will add a top level menu to the admin area for our marketing stats page. The add_menu_page() function allows you to specify a capability (the third argument) which determines whether or not the menu is shown.

Note that even though the add_menu_page() function itself takes the capability as an argument, we still need to check for it in the function which displays the content of the page.

This leads us into our next two functions nicely: current_user_can() and user_can().

If you want to check whether or not the currently logged-in user has a specific capability, simply use the following format:

if( current_user_can( 'any_capability' ) ) {
    // The user has the capability
}
else {
    // The user does not have the capability
}

If you would like to check whether or not an arbitrary user has a specific capability, use the user_can() function:

if( user_can( 45, 'any_capability' ) ) {
    // The user with the ID of 45 has the capability
}
else {
    // The user with the ID of 45 does not have the capability
}

In addition to capabilities, both fucntions can check for roles as well:

if( current_user_can( 'marketing' ) ) {
    // The current user is a marketing person
}
else {
    // The current user is not a marketing person
}

Creating User Types

While not an official term, I call different roles “user types” when they require many different front-end changes. Say you’re building a theme marketplace, for example. Apart from the administrator who oversees all (and the authors who would write in the company blog) you also have buyers and sellers. These are both registered users of your website but would require somewhat differing front-ends.

The profile page of a buyer would most likely show the number of things he’s bought, how frequently he buys stuff and when logged in, he would see a list of downloads.

A seller’s profile would be a portfolio of his work, his most popular items, and so on. When logged in he should probably see sales statistics.

Figuring Out Roles and Permissions

To make things simple, users either buy or sell, and cannot do both. Let’s create the two roles with a set of capabilities (off the top of my head…):

add_action( 'admin_init', 'add_custom_roles' );

function add_custom_roles() {
    $seller = add_role( 'seller', 'Seller', array(
        'read' => true,
	    	'delete_posts' => true,
	    	'edit_posts' => true,
	    	'delete_published_posts' => true,
	    	'publish_posts' => true,
	    	'upload_files' => true,
	    	'edit_published_posts' => true,
        'view_sales' => true,
        'moderate_comments' => true
    ));

    $role = get_role( 'administrator' );

		if( null !== $seller ) {
        $role->add_cap( 'view_sales' );
        $role->add_cap( 'view_others_sales' );
   }

    $buyer = add_role( 'buyer', 'Buyer', array(
        'read' => true,
        'add_payment' => true,
        'download_resources' => true
    ));

		if( null !== $buyer ) {
        $role->add_cap( 'add_payment' );
        $role->add_cap( 'add_others_payment' );
        $role->add_cap( 'download_resources' );
        $role->add_cap( 'download_others_resources' );
   }

}

The idea here is that sellers are like authors, who will store sellable items as posts. Therefore, they receive the capabilities of an author. In addition, they can also view sales stats for their own items.

In addition to viewing items, buyers can also add payments and download files related to items that they buy.

Admins receive all these permissions, but in addition, they may view the statistics of any other user, add payments to any account, and may download resources for any item.

Frontend Implementation

From here on out it’s a matter of using our role and capability checking functions to determine who sees what. Let’s take a look at a couple of examples:

Listing Users

If we list all the users on the website, we could show the items bought for the buyers and the items sold for the sellers. Here’s how:

<!-- 
	User Data comes from a WordPress user object stored in the $user variable 
--> 

<div class='user'>
	<div class='row'>
		<div class='threecol'>
			<?php echo get_avatar( $user->ID, 120 ) ?>
		</div>
		<div class='sixcol'>
			<h1><?php echo $user->display_name ?></h1>
			<?php echo $user->description ?>
		</div>
		<div class='threecol last'>
			<?php if( user_can( $user->ID, 'buyer' ) ) : ?>	
				<div class='counter'>
					<span class='number'><?php get_purchases_count( $user->ID ) ?></span>
					<span class='text'>purchases</span>
				</div>
			<?php else ?>
				<div class='counter'>
					<span class='number'><?php get_sales_count( $user->ID ) ?></span>
					<span class='text'>sales</span>
				</div>			
			<?php endif ?>
		</div>
	</div>
</div>

Most of this is plain old HTML, but the important thing to take away is how the counter is created. Note that the get_purchases_count() and get_sales_count() functions are fictitious (they are not part of WordPress, of course).

Of course, in a real world example we would need to make sure that only buyers and sellers are listed, and we might need to create a separate template for them completely (if the differences are numerous enough).

foreach( $users as $user_id ) {
    $user = get_userdata( $user_id );
    if( user_can( $user->ID, 'buyer' ) ) {
        get_template_part( 'userlist', 'buyer' );
    }
    else {
        get_template_part( 'userlist', 'seller' );
    }
}

When looping through our users above, either userlist-buyer.php or userlist-seller.php will be used, depending on the user’s role.

Conclusion

User roles and capabilities are extremely powerful tools in WordPress. Whenever you build a plugin which requires the implementation of special user-based functions, you should consider using them.

Apart from making your life easier (and more manageable) it will make the processes on your websites easier to follow and easier to backtrack any problems.

(jvb) (il) (jc) (js)


© Daniel Pataki for Smashing Magazine, 2012.


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress