Why must women pray behind men at the mosque?

Why must women pray behind men? Why is it that in Pakistan women have the worst place to pray when we need to pray in public and/or in the masjid? And also, why must men and women be separate in public? Isn’t that inconvenient? What is the wisdom behind all of this?

The wisdom in women praying behind men, which is the same as the wisdom in women wearing non-revealing clothes, is to take sexuality out of public interactions, so that people can get on with their lives and do what needs to be done without male-female sexual dynamics becoming a factor.

Men are designed to find women far more physically interesting than women are designed to find men. What this means is that having the women in front of the men at the mosque will cause more distraction, on the whole, than having the men in front of the women. Since the goal is to focus on God at the mosque, the logical thing to do is to not have the women in men’s sight. Since women do not find men particularly physically interesting, in general it doesn’t do any harm to have the men within the women’s sight.

Some will say it is men’s duty not to look at women lustfully, women shouldn’t have to dress a certain way or sit in a certain place just so that men wouldn’t be distracted by them. Islam deals with the issue on both ends, it asks both sexes not to look at one another lustfully, and it asks women to dress modestly so that if men do look, they do not see much to look at

At the mosque, it adds an extra degree of conscientiousness to have the women pray behind the men, to make lustful glances even less likely, so that proper respect for God is shown at His house.

We are all God’s servants and it behooves us to organize our public spaces in the way that is most likely to please Him. If having the women pray behind the men is more conducive to proper respect for God, and less distracting on the whole, than having the men pray behind the women, then it logically follows that it is best for the women to pray behind the men. The goal is not some power play or show of authority by the men, the goal is to show God proper respect, with both sexes being His lowly servants wanting to please Him.

As for why men and women can’t pray mixed like at church services, it is again because it adds an unnecessary gender dynamic to the act of praying at the mosque, which is unnecessary and not something God wants to be present in His house. Most of us are capable of praying alongside the opposite sex without any issue. But it is better not to mix, and since we want to please God, we do what is better. Amish Christians do the same, with the men and women sitting separately at church.

About separation in other public places, the point again is for public interactions to be civilized and free from lust. Islam has no issue with men and women interacting in public, it only wants to give the best shape to these interactions by removing potentially harmful dynamics. Each Islamic culture has its own way of trying to achieve this. Some cultures take the separation of men and women too far, and others have sensible policies that do not lead to inconvenience. Much of it is cultural tradition, there are no rules regarding separation of men and women in public in the Quran, for example.

I am sorry to hear that women do not have good places to pray in public in Pakistan. This could be a carryover from the past, where women venturing outside was far less common than now, so that there wasn’t much demand for better accommodations for women. Hopefully this will get better with time. In the United Arab Emirates, for example, the malls have large and well-maintained spaces for women to pray.

Patriarchy in the Quran

Stick to posting Islamic art and quotes. Otherwise, go learn about the patriarchy and power imbalances before flaunting your misogyny everywhere. May Allah guide you.

Islam is a patriarchal religion, where men get a degree of authority over their women in their households, and with that authority comes the burden of having to provide financially for all of their female relatives, so that in a devout Muslim society no woman will ever have to work, though they can if they want to.

That authority is balanced by the fact that a woman can get a divorce any time she wants, and she is protected by all of her male relatives against any abuses by her husband, so that if her husband abuses his authority in any way, she can always leave him to find a better man. The Quran calls on men to fear God, to be kind, to be just, and to defend the weak (which includes the women and children among them) but it also gives them authority in their households.

So while in Islam we believe in the equal worth of men and women, and in equal opportunities for both, the fact that God has given men a rank over women in their households is in the Quran, and ignoring this and pretending it doesn’t exist is throwing part of the Quran away because it disagrees with your preconceived notions, because you think your inane feminist-inspired moralizing is better than God’s guidance.

The Quran, 2:85: “Is it that you believe in part of the Scripture, and disbelieve in part? What is the reward for those among you who do that but humiliation in this life? And on the Day of Resurrection, they will be assigned to the most severe torment. God is not unaware of what you do.”

The Quran, 2:228: “And women have rights similar to their obligations, according to what is fair. But men have a degree [of authority] over them. “

The Quran, 4:34: “Men are the protectors and maintainers of women [qawwamoon, literally “people of authority who watch over and maintain standards…”], as God has given some of them an advantage [in rank] over others, and because they spend out of their wealth.”

If you have a problem with a patriarchal society, you are in the wrong religion.

I encourage you to learn Arabic and read the Quran to discover the wonders of a society where men are not considered worthless and disposable like in the West, but where they are respected as figures of authority, and where a woman enjoys the peace of mind that comes with having multiple God-fearing men dedicated to her welfare, knowing that she could never, ever be homeless or wanting of food and income while a devout Muslim male relative remains to her, knowing that she can marry and divorce whoever she wants, start a business, or do whatever she wants with her life as long as it doesn’t go against God’s commandments, enjoying a peaceful life among men who like her and respect her and will not let anyone abuse her.

You are free to leave patriarchy, which means all sustainable civilized societies (all societies that have an above-replacement fertility rate, i.e. that are not on the path to extinction like Japan and Western Europe), to enjoy life among some Stone Age tribe where matriarchy is the order of the day, or in the ghettos and trailer parks of America where men belong to their mothers and do not know their fathers, where non-existent fathers make a patriarchy a practical impossibility, since patriarchy means rule of the fathers.


/ 1 Comment on Patriarchy in the Quran

Feelings, censorship and gender in science: Is it unfair to say that women backbite more than men?

This is a follow-up discussion in regards to what I wrote in Dealing with a porn addiction.

Brother I understand that you answered that question as best you could, no one should be shaming you because you are offering advice that you could have easily ignored. However I would just say that to just mention how women may backbite was insensitive and unnecessary. Imagine all the stigma us sisters face on a daily basis, everyday we have certain brothers telling us what we should and should not be doing whilst they engage in haram activities. (1)

So imagine when someone asks you about porn addiction that has nothing to do with women backbiting, and even then we are bought into it, I’m sure as an understanding brother you can see. Tomorrow if someone has a problem yet I say “Don’t worry it’s less of a sin as millions of Muslims especially men, don’t grow their beards to the proper length, you are no worse than them”, look how insensitive that seems. I hope I have not offended you brother, it is our duty to guide with kindness and openess

Thank you for your kindly phrased message. I understand what you are saying, and I’m sure you are right when you say you have suffered unjust criticism.

I have never considered women a class, like feminists imagine, separate from men. I consider them humans, my equals, and hold them to the same standards. I don’t walk on eggshells when I discuss men’s problems, and I will not start walking on eggshells when discussing women’s problem’s.

I consider you my equal, and that means we both should be free to speak our minds. You shouldn’t be silenced if you have a truth to speak just because it may hurt some men’s feelings, and I shouldn’t be silenced if I have a truth to speak just because it may hurt some women’s feelings.

It is certainly good manners to not bring up negative facts about someone in ordinary daily interactions. You do not call an overweight person fat even if it is true.

But if I’m trying to solve a technical problem, I expect people to put their feelings aside, to sit down like adults and to discuss the problem rationally, and that is what I was doing in my answer.

If I’m doing a scientific study on finding ways to reduce backbiting among women, would you call it insensitive? I’m sure many would, that it is somehow oppressive and unjust to focus on females, that if I discover a method that works well in preventing females from backbiting, I should shove it under the carpet in case some woman’s feelings is hurt, even if it will do them good in the long-term.

We cannot have progress if we are not allowed to speak our minds freely, if we have random no-go zones where we are not allowed to analyse things in case it hurts this group’s feelings, or that group’s, or that group’s. That’s censorship and regression, that’s not progress.

It is like saying I should not talk about the unhealthy effects of being obese because it will hurt obese people’s feelings. Should we just throw out all obesity-related research in case some obese person comes across it and has their feelings hurt?

I was helping put a mostly-male problem into perspective using a mostly-female problem, as an intellectual exercise. I consider women equals, not superiors and not inferiors, but equals, humans to be treated with the same standards, not to be treated like children, but treated equally, like I would treat any man, and I certainly never worry about hurting men’s feelings when I bring up facts that reflect negatively on them.

If men are unjustly criticizing you, I fully support your right to fire back at them and put them in their place. I defend your right to speak your mind. And I defend my right to speak my mind. We are not enemies, and we are not different species. We are both humans, and we can treat each other as such.

We do not achieve equality by enforcing double-standards where a male speaker is not allowed to say certain things in case it hurts women’s feelings. We achieve equality when no one thinks about their own sexual parts but can consider the problem and its solution rationally, like adults. The speaker says men have a problem with ignoring their wives? Fine, I will try to be a better husband. The speaker says that women have a problem with ignoring their husbands? Instead of getting offended that a person of the opposite sex is pointing out a fault, women can choose to benefit from it, “Fine, I will try to be a better wife.”

This is equality, where I am not forced to treat you like a “woman”, but like a human, and where I do not patronize and belittle you by censoring my speech in case it hurts your fragile feelings, but where I can treat you like I treat any man, expecting you to be intelligent and confident enough to accept it and roll with it.

These are my standards when it comes to public speech. In private one-to-one interactions, it is good manners to hide people’s faults, to not criticize, and to make them feel good about themselves. But in public, for example if I’m doing a scientific paper studying women’s psychology, I will not sugarcoat my findings just because it may hurt women’s feelings, in this case telling the truth takes precedence over being nice.

And as a nice person, I will never mock an obese person by calling them fat, and I will not let others do it if I can stop them. But I will happily continue researching the eugenics of obesity (how genes affect obesity, and how obesity affects future genes) like I currently do no matter how many obese people are offended by it.

In the same way, I will continue to be frank and straightforward when writing about women, since in my research writing, truth always takes precedence over being nice. But when dealing with women in my personal life, I will always be as kind, gracious and uncritical as is required by good manners, civility and Islam.

A reply from a reader

I feel you were wrong in saying that women do more backbiting. Not saying it is in itself true or false ( I really dont think they are any reliable studies) but I think it was completely unnecessary to say it the way you did. You could have said simply that many Muslim backbite it would have been enough. No need to drag women into it. Im not attacking you or anything just saying there might have been a better way to go at it.

If I were a woman and jokingly mentioned that fact, I don’t think anyone would be bothered. The only reason that it is “wrong” is that a male said it. And if I had mentioned a fact that reflected negatively on men, not women, I don’t think anyone would be bothered.

I have never bought into the Western nonsense of treating women like children to be pampered to. I like to treat them like my equals, which means that I speak my mind without bothering what type of sexual organs my listeners have. I consider you all the same, we are all humans.

So no, I don’t think I did anything wrong. Having a porn-watching problem is a mainly male problem, and having a backbiting problem is a mainly female problem. I have heard many women agree with both of these facts. Mentioning both problems together is a very useful intellectual exercise to help put the problem of porn-watching into context.

If I had mentioned a positive fact about women, you wouldn’t be upset. You are thinking like a politician, “he said something negative about my interest group without belonging to said group, which makes it automatically wrong.”

What you really want to enforce is that all men should be able to talk about women, as long as they stick to mentioning positive facts, as long as they maintain a parallel-reality of cotton candy and fluffy bunnies where no woman’s feelings can ever get hurt.

I prefer to speak my mind freely, and I prefer to treat women like adults. I never worry about hurting men’s feelings in my research writing / answers, and I will not start worrying about hurting women’s feelings.

If you disagree with this, that’s your right. I, however, will continue to be as I am, focusing on serving God, and having my allegiance only to truth. If people’s feelings get hurt when I mention a fact like how unhealthy obesity is or how Indians can never compete with the Chinese in innovation, at least not for the next 500 years or so, I’m sorry. I will never mock someone or say any truth that may hurt their feelings in private interactions. But on my blog, where I want to teach and guide people, I will speak the truth, and I will not self-censor my speech like a politician.

If this is unacceptable for you, if you’d like me to hire someone to review everything I say in case it may be considered discriminatory to one of a dozen interest groups, then you are in the wrong place. I have always been a free-speech and anti-Political Correctness activist.

You are right that I didn’t have to bring women into the discussion. It was a perfectly voluntary act on my part.

My mother and sister have a sense of humor and the last thing they would do would be to get upset over what I wrote. I think they have got things right. I treat all women like them, intelligent and confident in their femininity. And if I ever say something stupid or unjust, they will not let me get away with it but will correct my mistake, the way a man would do.

Of course, I won’t go around speaking negative things about women saying that they have to deal with it. That’s like calling overweight people fat, it is rude even if it is true. As I said, in private interactions, I do what good manners, civility and Islam require of me. And in my research writing or answers, I write frankly without bothering who gets offended.

I encourage you to open your heart, to see how an innocently made remark done in good faith and with the intention of helping someone should not be criticized just because a person of the wrong sex said it. Stop thinking like a Western politician and more like a fair-minded Muslim with a sense of humor.

You could say that context matters, that in that particular context it was wrong for me to mention women since I have many female followers whose feelings could get hurt. I disagree. It is my personality to be frank in my writing and to treat women the way I treat men, considering them really my equals instead of patronizing them by treating them like a protected minority.

Dealing with a porn addiction

Tumblr question:

How can I deal with porn addiction?

The short answer is that if you do sufficient worship and Quran-reading so that the afterlife feels more important than the present life, or as important, then giving up any sin becomes the easiest thing in the world. Your problem is not porn, but the fact that your heart is not sufficiently soft, humble and submissive to God. This is the problem that needs to be fixed, and the fixing of it is through dedicating at least an hour of every day to voluntary worship, whether it is through reading the Quran, or praying extra prayers, or sitting after every obligatory prayer in supplication.

Once you continue on this path for a few days, your heart will soften and become submissive, and your awareness of God’s nearness will increase, and your eagerness to seek to serve Him through good deeds will increase as well, so that you enter a state where sins become unthinkable.

Always ask yourself how important the afterlife feels to you. If it feels faraway and unimportant, you have failed at keeping God’s remembrance alive in your heart, and this is what you must work to fix. You know you have reached the necessary state of piety when your record of deeds feels like a real object to you. You think about adding good deeds to it, and worry about the sins recorded on it, so that you continuously ask for forgiveness, since you can never be sure if God has forgiven all of your sins.

Once the afterlife feels so real that it is not just an intellectual idea, but something that causes emotions in you (thinking of Paradise makes you feel excited with joy and longing, and thinking of the Hellfire causes you fear), then you know that you have finally managed to balance the present life with the afterlife.

Being addicted to any sin can only come about when one is attached to the present life, when the afterlife is nothing but a faraway idea, rather than a real, living and breathing thing that is only a heartbeat away. This is the disease that needs to be cured, and curing it will cure all sins, not just a particular sin.

Therefore do everything you can to cause the afterlife to feel real in your heart. Read the Quran, supplicate to God, and continue praying, until your heart submits.

And repeat that every day. This is nothing something that you can accomplish and leave its trophy on your shelf. Faith is something that needs to be continuously recharged, every day of your life. You must work every single day to keep the afterlife real in your heart. Every morning will be a new day in which the afterlife will fade from your heart, and you must exert daily effort to recreate its reality. Without this, no matter what short-term success you achieve in avoiding sins, you will always fall back into it.

God will not burden you with more than you can bear. If you cannot stop it, then make up for it by asking for forgiveness, reading Quran, and praying tahajjud.

Always remember this verse of the Quran: “We have not placed any hardship for you in (this) religion.” (22:78).

There are no clear texts (Quran or hadith) that deal directly with watching porn. This is a matter of conscience between you and God. God is a kind and understanding master, and He knows you better than yourself. If you cannot stop, then continue returning to Him in repentance, He will see your sincerity and your efforts, and that is what matters.

Watching porn is less of a sin than backbiting (gossiping about people), yet hundreds of millions of Muslims, especially women, engage in backbiting all the time. So know that you aren’t any worse than them.

In ten years, when your hormones have calmed down, you will find it much easier to resist this sin.

People’s reactions to my answer, and my counter reactions

I literally am unfollowing you just for the way you answered this ask. “Especially women. Know that you’re no worse than them” wow……. 

I’ve lived 27 years in this world and know that backbiting is ten times worse among women than men. I imagine if I said a porn addiction is much more of a problem among men than women you wouldn’t complain :), but both of these are statistics. “No worse than them” meant no worse than all the Muslims who engage in backbiting, including men and women.

I know in the modern culture of what I call fashionable nonsense, calling attention to statistics that reflect negatively on a protected minority (women, racial minorities, etc.) is a big no-no. Personally, I think the truth is preferable to lies, and if there is a statistic that reflects negatively on women, and another statistic that reflects negatively on men, I have no qualms about admitting both.

As a Muslim, I will never, ever deny a truth just to keep up with fashions and political correctness. My allegiance is to the truth, not fashion.

What the?? It completely sounds like you’re belittling the sin and desensitising people to how horrendous it is! It’s like you’re saying “don’t worry about murdering people, did you know that killing someone is less of a sin than taking out bank loans with interest? One day you’ll learn to control your rage and it won’t be an issue for you.” I’m sorry but that’s definitely not the advice to give to someone who sincerely desires to stop. It’s almost like you’re encouraging it.

I disagree. I encourage people to deal with these matters as a matter of conscience, between themselves and God, to read the Quran, and to seek a solution instead of wallowing in guilt and despair. It is a fact that controlling one’s sex drive becomes much easier after the age of 30, there is no shame in admitting this.

One more thing you’re assuming that the person sending you that p*rn ask is a man?? I’m a woman who used to suffer from that anon’s same problem btw! Let’s see how you respond to this 🙂

You are right, I shouldn’t have assumed they are male.

Then doesn’t that mean that your whole argument about men’s sex drive is invalid??

No, it just shifts the time bracket. For men, the most challenging time is their teens and early twenties. For women, it is their mid-thirties. However, female libido is quite lower than male libido, so the most challenging time point for women is actually the same point on the graph when libido becomes manageable for males, meaning that the majority of women will never experience the immense pull that porn has on men:

From: http://geniusbeauty.com

To the anon suffering from p*rn addiction : use a website blocker extension from google&block the websites (or search words) to stop yourself from accessing it(set a long password that you’re not likely to remember then delete the document with that password or ask someone to set it for u)also avoid spending time on your own+stop using earphones&try to find a hobby to keep yourself busy+ make lots of duaa&Thikr whenever you get the urge to watch- it’s hard but making duaa for you- Hang in there

I have been receiving questions about porn addiction for the past 10 years. I have read the opinions of many respected scholars, I have read stories of many people suffering from the problem, I have even gone so far as to read a book on curing it: The Porn Trap.

And what I’ve learned is that that type of common sense advice rarely, if ever, does sufferers any good. It doesn’t matter that it makes sense, what matters is that once it is applied by a real-life sufferer, it doesn’t work.

The solution is to keep one’s faith as best as one can, continue seeking a solution until God gives them one (which could be very different for different people), instead of despairing. And all the while acknowledging that biology plays a key role in this issue. There are almost no 60-year-old Muslim men suffering from a porn addiction, because the sex drive becomes easily manageable for most men after the age of 30. This is a very important fact and it must be integrated into any solution idea we come up with.

Same anon as before this time Im addressing op : I think you handled the ask very badly, it’s a good thing to remind someone of Allah’s mercy and that it’s never too late to repent but you shouldn’t belittle watching p*rn- it’s a HUGE sin not to mention how harmful the p*rn culture& industry and supporting it is, also you’re not the one who decides which sin is worse than other and you’re in no position to judge or compare genders’ sinning in that matter. I must say I’m disappointed, man.

Shaykh Yasir Qadhi says watching porn is a minor sin, and I agree with him. Saying watching porn is less of a sin than backbiting is not belittling it, it is putting it in proper perspective.

Making a huge deal of porn will neither solve the problem nor help sufferers who are doing everything they can to avoid it.

To a Muslim, all sins are great, because they are all betrayals of God’s trust and respect for us. Knowing this is sufficient to make any fair-minded, open-hearted Muslim seek to avoid porn as best as they can.

I have every right to speak my opinion on this matter, and if you know better, you are free to present your evidence.

Islam is not a bureaucratic religion like many people think, where scholars form a priesthood that decides and thinks for everyone else. I can read the texts myself and make up my own mind. That’s Islam for me.

I will never, ever let another person do my thinking for me if I can help it. All authorities, scholars and texts must be questioned to ensure that logic, fairness and truth are respected and that no one gets more power than they need to do their job in serving the community.


Managing stress and loneliness

Salam alaykum how may I manage stress and focus on myself, sometimes I feel lonely-no one contacts me I’m ok with it I really need to put myself first

Alaikumassalam wa rahmatullah,

There are hundreds of books dedicated to those topics, everyone is different so no one solution that works for everyone.

You say you feel lonely. That might be the root issue. According to Loneliness: Human Nature and the Need for Social Connection by the renowned scientist John T. Cacioppo, loneliness is a disease. It increases inflammation in the body, slowly blocks arteries, causes diabetes, and leads to depression, and there is no cure for it other than to stop being lonely.

Being lonely means to lack meaningful social connection with others. You don’t have to be alone to be lonely. You can have many people around you and still feel lonely.

An easy way to start solving this problem is to use your tumblr to find people to interact with on a daily basis. To cure loneliness, we need to feel that we matter, that people care about what we do and say. And on tumblr, if you have many followers, as you interact with them, as they read your posts and reply to them, that can give you some of that feeling and in this way reduce your loneliness.

Doing anything that makes you feel cared about, that makes you feel like you matter to someone, will reduce your loneliness. You can do it online, or do it in real life by finding ways of connecting with people.

As for managing stress, one thing that helps is to read the Quran. If you dedicate an hour a day to reading the Quran, slowly the afterlife will start to appear more important to you than the life of this world, and this will make all of your worldly problems appear small and unimportant, which will take the stress out of daily life.

What to do if you have intentionally missed many days of prayers

Asalam alaykum I have not competed two days worth of prayers how do I seek forgiveness/ good deeds and rewards I’m fearful of the punishment I felt lazy them two days that I was staying at a friends house Am I able to make up for it 🙁 May Allah reward you

Alaikumassalam wa rahmatullah,

Ask for forgiveness and redo as much of the prayers as you can as soon as you can.

Think of God as a kind teacher who wants you to do what is best for yourself. He will not abandon you just because you’ve made a mistake or did wrong toward yourself. He is always ready to forgive you, as long as you do not rebel against Him, as long as you do not make sinning and disobedience a habit that encircles your life.

You will sin many more times throughout your life. What matters is to always return to God, instead of living in sin perpetually, risking the possibility that you may die without repenting.

53. Say, “O My servants who have transgressed against themselves: do not despair of God’s mercy, for God forgives all sins. He is indeed the Forgiver, the Clement.”

54. And turn to your Lord, and submit to Him, before the retribution comes upon you. Then you will not be helped.

55. And follow the best of what was revealed to you from your Lord, before the punishment comes upon you suddenly, while you are unaware.

56. So that a soul may not say, “How sorry I am, for having neglected my duty to God, and for having been of the scoffers.”

57. Or say, “Had God guided me; I would have been of the pious.”

58. Or say, when it sees the penalty, “If only I had another chance, I would be of the virtuous.”

59. Yes indeed! My Verses did come to you, but you called them lies, turned arrogant, and were of the faithless.

[The Quran, verses 39:53-59]

Back to the question of not completing the 2 days worth of prayers am I able to pray now If so do I start with fajr and end at isha or start at isha then finish at fajr? May Allah reward you

There is difference among scholars on what is best to do in your case, since you intentionally stopped praying. As far as I know, there is no clear text (Quran or hadith) that deals with your specific case. Many scholars say the prayers should be redone, with the important exception of Ibn Taymiyyah, Ibn Hazm and some of Imam al-Shafi`i’s followers, who say that when the prayer is abandoned intentionally, there is no need to redo them, that one should only repent and start praying again from that point on.

Personally I would redo the prayers, since it is only 2 days worth of prayers, just to be on the safe side. I would start from the earliest missed prayer to the latest.

If it had been many months worth of prayers, I wouldn’t redo them, I would do the sunnah prayers and pray tahajjud every night for months to make up for it.

The point of the Islamic acts of worship

A question received on tumblr:

What are the importances of acts of worship Prayer, zakat and fasting etc

At the most basic level these acts reaffirm God’s important in our lives. We Muslims cannot ignore God, saying “we have faith” and then go for days without thinking about God. The prayers interrupt our lives five times a day. Fasting interrupts a whole month of the year.

As for zakat, it provides basic income to the poor. If the people of the United States paid zakat, it could amount to $100 to $500 billion dollars a year, meaning that within a few years there wouldn’t be a single homeless or poor person in the country, and every poor person (belonging to the bottom 50% of society) would get a monthly income of $1000 or more from zakat.

As far as I know no Muslim country properly applies the zakat system, which is why there is so much widespread poverty in countries like Egypt. Zakat has to be taken, it is not a voluntary act. Most rich people are not generous and would rather not pay 2.5% of their uninvested wealth to the poor every year, they would rather do as the Jews and Christians of America do, lending their wealth to the poor and charging them 5% or more interest.

In the zakat system, the poor charge interest on rich people’s uninvested wealth, the money they hoard in their bank accounts. In America’s usurious system, the rich charge interest on the poor, to the tune of more than a trillion dollars per year. American taxpayers paid upwards of $200 billion on money borrowed from usurers to pay for government expenditures, which is why the rich and powerful of America constantly want to increase the size of the military and to instigate new wars, such as with Iran and Russia. War requires spending, and the money for it has to be borrowed from the rich, and the interest on that money has to be paid by the average taxpayer.

For the rich, war always means money. Islam breaks this cycle of evil and destruction by prohibiting usury (all charging of interest) and enforcing zakat.

As for other acts of worship, they all have some wisdom if you look into them.

What to do when your spouse is less religious than you

A question I received recently:

I am in my early twenties and have married a woman who comes from a Muslim family. After marrying her, I have found that religion is not very important to her. I had wished to marry a woman who was my equal in faith, so that we could create a faithful family together. I feel like I have made a mistake in marrying her, and I don’t know where to go from here. Why did God allow me to marry her?

My answer:

It is normal to start having doubts after marriage when you have no previous experience with it. Many ideas and assumptions about the other sex will be proven false or inaccurate once you are living the reality of marriage.

Women are generally more liberal than men and laxer when it comes to religion. I come from a conservative Muslim family but I’ve had trouble convincing close female relatives to stop engaging in negative gossip about people (i.e. backbiting, ghaibah). I know a woman who is a civil engineer (so she is educated and intelligent enough to know better), and even though she went to an Islamic boarding school where they recited Quran every night and sometimes stayed up all night for prayer, she continues to think it is her every right to gossip about people.

When dealing with women, always remember Imam al-Shafi`i’s saying: “Be harsh on yourself, easy on others.” You shouldn’t hold your wife to the same standards as yourself, and if she does the minimum that is requested of her by religion, you should be thankful for that.

I grew up knowing many great men in my extended family, highly religious, kind and observant men. But almost none of these men had wives who could match them in faith, and some had wives who only did the minimum and didn’t care about religion at all. This hasn’t stopped them from bringing up good religious families.

In a household, men and women are not equal when it comes to authority. The Quran gives men a degree of authority over women (Quran 2:228, 4:34), and perhaps part of the reason for that is that men are, in general, more observant and more conservative, though a minority of women can be found who are like this too. It is a man’s duty to keep standards high in his household, preventing lax behaviors like not praying, not fasting or eating what is not halal, though he must do this with love and kindness, not with authoritarianism:

“Invite to the way of your Lord with wisdom and good advice, and debate with them in the best possible manner.”1

If your wife does the obligatory deeds (praying, fasting, etc.) and avoids haram (alcohol, interest, etc.), then this is the most you can expect of her, and leave it to her as a free-willed human being to make up her mind to do more if she wants. If she doesn’t do the obligatory deeds or engages in haram, then you have a clear right to give her an ultimatum, for her to come back to the Straight Path and do the minimum of what’s requested of her in Islam. If she doesn’t, then in effect she is refusing to do what the Quran asks of her, meaning that she is denying its truth, and in a way she is a non-believer. There is no obligation for you to stay married to her in such a case.

If she does the minimum required of her, then the Quran encourages you to be patient and to rely on God to steer your destiny for you. The Quran says in 4:128 that when a (devoutly Muslim) husband and wife are in disagreement, making peace is always the best option, and warns them to be wary of their ego’s greedy desire for better things.

One of the companions of the Prophet (peace be upon him) didn’t like his wife. The Prophet told him to fear God and keep her, this advice of the Prophet to him is recorded in the Quran in verse 33:37. The companion (Zayd, the only companion mentioned by name in the Quran) ultimately decided to divorce her. So, while Islam teaches that a man should hold onto his wife, a man’s right of freedom of choice is respected.

A man’s role in life is to acquire worth, marry a woman, have children, take care of his family, and in this way continue Islamic civilization. For this to be successfully done, it is not necessary for the woman to be as religious as the man. Ideally, of course, that’s what we want, but in reality, the nature of men and the nature of women is different, and you will have a very hard time finding women who cares about religion as much as you do.

It is better to be practical. To be thankful for what God has given you and to try to make the best of it. Do your best to be kind, generous, patient and forgiving, rather than judgmental and demanding. Some men mistakenly try to force their women to become what they want, only to give up after years of futile effort. You must learn to trust God and leave it to Him to steer your destiny. If you do separate in the end, you should be able to say “I did my best to make things work, but it didn’t work out.”

I am not saying to be like a feather in the wind, going wherever life throws you. You must rather always face God, working to please Him. You must not face your wife constantly trying to change her. She is only a small part of the big picture. You are a servant of God and you were made to serve Him. He recommends that you try to make your marriage work even if you are not pleased with your wife. Since you are facing God and aiming to please Him, you will be kind, generous and non-judgmental toward your wife as long as she does the minimum that Islam asks of her. Whether you think she deserves this lenient treatment or not, you are not doing it for her, but for God, and you expect your reward from God.

Having an unsatisfactory wife is a difficult test since you might be thinking that maybe this is how things will be for the rest of your life. You do not want to be stuck with someone who doesn’t live up to your standards. You probably wish to get in charge of your destiny, get rid of her and get a far better woman in her place.

The problem with this is that 1. It is not your job to manage your destiny and 2. No matter how good the imaginary new woman is, assuming you can find her and marry her, you could run into new and unexpected problems that could make your life with her miserable, she may develop an illness, she may suffer an accident and go blind, she may have a bad family who constantly interfere with your life.

As a Muslim, you believe that God is the King of the universe, and that He has the power to do anything He wills. He had the power to prevent your marriage from taking place. He had the power to make you marry the perfect woman. But He didn’t. And today He has the power to swiftly end your marriage with little effort on your part, and He has the power to give you the type of woman you desire. But He doesn’t.

It is God who manages your destiny, taking you from one stage of life to another, testing you, helping you learn, helping you grow in wisdom, understanding and kindness. Your focus should be on God, He can take your life anywhere He wants, and He has the power to do it this instant if He wanted to. Since He is not doing it, that should tell you something. You must do your best in the current test you are in, you must follow His advice that trying to make your marriage work is better than separation, and the Prophet’s advice to fear God and hold onto your wife, and leave it to God to change your situation if and when He wants. You must expect only from God and ask only of Him.

You could of course ask, “What if this test is not intended for me? What if I will needlessly suffer for nothing?” If you put your focus on God, since you know that He has the power to take you out of any unwanted situation, then you will know that there is no such thing as needlessly suffering. If you keep your wife for the sake of God, God will reward you for it, both in this life and the next. And if He doesn’t want you to keep her, He will make it easy to separate.

If your marriage somehow naturally falls apart, with both of you, or at least you, trying your best to keep it together through non-judgmentalism, forgiveness and generosity, and you reach an agreement to separate without any negative emotions, without guilt and without fearing that you might be doing the wrong thing, then you can take that as a sign that God approves of the separation.

But if things go along normally, if things are good enough, if the thought of separation contains tremendous amounts of uncertainty, guilt and fear, then that is your sign that it is not time to separate, that if you were to work toward separation, you’d be going against the flow of the destiny God has chosen for you. You can do it, like Zayd did, since God respects your freedom. But it is better for you to accept it and do your best, constantly asking God for forgiveness and betterment. If you reject this test, God will give you an equally demanding test, because God will never stop testing you.

Until the day you die, if God loves you, He will constantly give you new opportunities to prove your patience, your generosity, your worth. If He gave you the perfect life, you’d have no opportunity to prove these things.

What I would do in your situation is this: I would do my best to improve myself as a Muslim, reading as much Quran as I can, praying tahajjud and constantly asking for God’s forgiveness. I would do my best to be kind and forgiving toward my wife no matter how distasteful I find her behavior. I would do more than what is strictly necessary to make the marriage work, for God’s sake, even if it displeases me to do this. I would always try to be the bigger person. I would put my focus on God, recognizing His power to change my wife and my life in any way He wishes, recognizing that all good things come from Him, not from my own efforts.

And if after all of this, I receive a clear sign that my marriage should end (she decides she wants divorce and is intent upon it), then I would do what is necessary in that situation. Maybe you will stay married to her for the next ten years, and after that separate to enjoy the type of life you desire. Or maybe in some years she will change into someone with as much faith as yourself, and then you may be glad that you stayed with her.

So my advice is the Prophet’s advice, peace be upon him: Fear God and keep her.

And leave it to God to take care of your destiny. Trying to steer your destiny is a heavy and exhausting burden. Free yourself from that burden. Enjoy the life that God has given you, do your best, constantly ask for God’s forgiveness, and know that God can put you in a better place anytime He decides. If you want to speed this process up, you can do it through worship, asking for forgiveness, and avoidance of sin.

To improve your situation in life, raise your status in God’s eye, and He will do it for you better than you ever could. Trying to improve your situation in life through your own efforts, rather than through God, will always lead to new situations that are as equally difficult as the one you left.

Patience means to go against your desire for the sake of God. If you patiently keep your wife despite your wishes, you will be rewarded for your patience. Patience might possibly the greatest virtue of a believer. The angels commend the believers on their patience when they are about to enter Paradise, as the Quran describes in Surat al-Ra`d:

22. And those who patiently seek the presence of their Lord, and pray regularly, and spend from Our provisions to them, secretly and openly, and repel evil with good. These will have the Ultimate Home.

23. Everlasting Gardens, which they will enter, along with the righteous among their parents, and their spouses, and their descendants. And the angels will enter upon them from every gate.

24. “Peace be upon you, because you endured patiently. How excellent is the Final Home.”

And do not try to push your wife to change for the better, or to buy her Islamic books, forward her Islamic articles or make her go to lectures hoping she will be better guided. Calling people to Islam should never be inflicted on people. They must seek Islam themselves.

It is God Who guides people, it is not people who guide people. Therefore no matter how hard we try or wish that someone was guided, our efforts and wishes may never come true.

You cannot guide whom you love, but God guides whom He wills, and He knows best those who are guided.2

God will not leave all the tests to you and neglect your wife. He will continue testing her too to help her grow and to guide her, but the stage she is in could be very different than yours, and the types of lessons she needs could be nothing like you imagine.

Leave it to God to guide her, He will do it in the best way possible.

Temporarily Curing ADHD / Chronic Fatigue With a Dopamine-Sensitizing 5-Hour Fast Followed by a Jolt of Dopamine

I was almost entirely unproductive for the first two weeks of Ramadan due to having to fast from 4 AM to 7:30 PM, which, for the non-Muslims reading this, means no food, no water, no caffeine and no supplements between these hours, which where I live means 15.5 hours of fasting.

As a contractor, if I can’t work, I cannot make money, so I urgently needed a way to get my productivity back. Regardless of how much caffeine I had after breaking my fast in the evenings, I felt unmotivated and unable to focus on my programming work.

After much experimentation, I discovered the solution. This solution enabled me to be extremely productive for the last two weeks of Ramadan, making up for all of the lost hours of work in the first two weeks.

Below is the solution I discovered, generalized to a non-Ramadan context so that anyone can use it. This is not a great long-term solution, but if you are desperate to feel productive, it is worth a try until you find something better.

1. Fasting for 5-8 hours after wake up

Do not eat or drink anything, especially no caffeine and no other supplements. This pleasure deprivation causes changes in the brain that make it possible to cause it extreme stimulation afterwards. Water might be OK, though in my case I didn’t have any water, feel free to experiment and comment below.

I rearranged my sleep schedule so that I started waking up somewhere between 12:30 PM and 2:30 PM, going to bed after 4 AM. If you are not doing an Islamic fast, rearranging the sleep schedule is not necessary.

I cannot say exactly how many hours are needed, but starting with a 5 hour fast would be a good idea.

The fast is really uncomfortable, naturally. You are depriving your brain of what it desires, making it feel bad so it can feel good later on.

2. Having a very small carb-heavy meal upon breaking the fast, another small meal 4 hours later

Upon breaking the fast, I would have half a slice of bread (45 calories) with jam and butter, and a cup of strong black tea with honey in it. The whole meal was probably about 200 calories.

Due to my pre-diabetes, I had to have 1000 mg of berberine, 300 mg banaba extract and 600 mg olive leaf extract. I also discovered 230 mg ALA made me far more energetic and prevented my usual post-meal dry eye.

About 4 hours after my first meal, I would have another similar meal, that would help me continue working for 2-3 more hours.

After that you can have your final meal of the day, which if too large would affect your sleep quality and your ability to be productive the next day. These days I’m trying a 600-calorie diet to cure my pre-diabetes, my goal is to love every last pound of unneeded fat that I have (perhaps 7 more pounds to go), so my last meal of the day, having it an hour or so before bed, was quite small, and carb-free.

3. Zinc and copper

I had 12.5 mg of elemental zinc from sulfate and 2.5 mg copper from copper glycinate. Both of these trace elements encourage neuronal excitation, making you feel more motivated. Too much causes excitotoxicity, therefore I do not recommend ever going above the above doses.

Zinc improves energy production and does something to the brain that makes it more receptive to dopamine, or at least it feels like that.

4. 120 mg L-Dopa with green tea

L-Dopa a supplement that increases dopamine in the brain. This is a dangerous supplement to use in the long-term, because it desensitizes your dopamine receptors by overfeeding them with dopamine. The green tea is needed to prevent L-Dopa’s negative side effects. I took half a teaspoon of matcha for this. This might be broscience, but there are a lot of people saying the green tea or green tea extract is necessary.

It is possible that the L-Dopa is not necessary. I took it because I thought it wouldn’t hurt to try it for two weeks until Ramadan ended. Now that Ramadan is over I have stopped taking L-Dopa and I seem to be going through withdrawal, confounded with also stopping tianeptine.

5. My usual stack from before Ramadan

I continued to take smaller doses of my supplements from before Ramadan. That meant 300 mg piracetam, 2 Perika, 1 carotenall on some evenings (not sure if I need this supplement), 25 mg tianeptine sulfate, 2 nettle root extract.

I have stopped taking tianeptine because I ran out of it, and I have felt very down for the past two days because of this, and perhaps also because of stopping L-Dopa. Tianeptine is a real thing and many people have reported it. I still love tianeptine and will probably order some more to use it occasionally. It is really good at making me productive after a night of bad sleep.

6. Protecting the liver

Earlier in the year I had some liver damage from high doses of vitamin A and from spirulina. I have continued to have very mild liver tenderness and sometimes pain after taking supplements. Tianeptine, piracetam and nettle root extract seem to be the biggest culprits.

For the above reasons, I started taking NAC regularly, and more recently stated milk thistle. These days I always take 1000 mg NAC and 1200 mg milk thistle every time I take supplements, and this has made liver pain a rare occurrence.

7. Caffeine

I would have many cups of coffee from breaking the fast until 4 hours later when I had my second meal. Normally I would stop taking caffeine 8 hours before bed, but on this program 4 hours before bed seemed to be good enough, perhaps due to the fact that I was taking tianeptine, which makes up for the effects of sub-par sleep.

8. Exercise

Exercising during the fast seemed to lead to better results afterwards. But I stopped exercising a few days into the program because it wasn’t strictly necessary, and because my low-calorie diet was making me feel really de-energized during the fasting hours.


The goal of this program, as the article title says, is to deprive the brain of stimulation for a number of hours, then to give it a shock of dopamine-increasing substances, including a carb-containing meal with a sweetened drink. The contrast in dopamine between the fasted state and the fed state is sufficient to cause your (well, at least my) motivation skyrocket. In fact a few times I felt too stimulated, unable to focus on a single task because I kept wanting to write down an idea or a few paragraphs for one of the books I’m working on. Olive leaf extract seemed to help with focus.

Another thing that seemed to help with focus was working with all of the lights off (while wearing blue-light filtering glasses to protect the eyes). Working in the dark is an old focus trick I discovered years ago, but doesn’t always work, perhaps dopamine has to be high to begin with.

Long-Term Concerns

L-Dopa is used to treat Parkinson’s disease and has serious long-term side-effects. For this reason you must never rely on it. Too much of it causes dangerous recklessness and impulsiveness. If you feel a “buzz” from it, you’ve probably had too much.

Tianeptine has amazing effects, but the fact that it gives me liver pain, and the fact that it causes withdrawal, makes me hesitant about using it in the long-term.

Now that Ramadan is over, I’m working on developing a new program where I can do without most of the supplements I take. I’ve discovered that 2-minute bouts of intense weightlifting (deadlifting a 160 pound weight) bring back my motivation and ability to focus, work and write when nothing else can. What I plan to do is start doing these 2-minute bouts throughout the day and see what happens.

On the evolution of language

Languages evolve or devolve until they reach the state of minimum energy consumption necessary for its speakers to conduct their affairs.

Low IQ descendants of speakers of English will quickly lose most of their vocabulary and complex grammatical structures if they end up on an isolated island for generations. While the complexity of the language will increase if there is a general rise in IQ as the population of speakers is held steady or increases.

The way of speaking of the upper class seems unnecessarily complicated and pretentious to the average person. Some of the upper class do make their speech more complex to show off and differentiate themselves from those below them, but since the upper class has a higher IQ than the lower classes, their speech will always be more complex.

Some people who are desperate to enter the upper class, or who are already there and have nothing better to do with their sad lives, go out of their way to use rare and unnecessarily complex words and structures to impress others with similarly sad lives, because it is apparently a mark of intelligence to use ten words when five would do.

An actually good and intelligent speaker (like George Orwell) will use the minimum number of words necessary, and the simplest available, to express their ideas. The writing’s complexity only increases when the ideas demand it. Complexity is never used when simplicity would do just as well. While a pretentious speaker, like so many philosophy professors, will use a thousand words when a single sentence would do.

A guide to adding Google Drive (and OneDrive) upload functionality to Froala

Froala is a great JavaScript editor until you try to extend its functionality. Its documentation is horrible and there is little extra functionality you can add without having to do a lot of reverse-engineering and reading of GitHub comments.

Below is a guide to my solution for adding a Google Drive button to the Froala editor.

Here is the custom black and white icon I use for Google Drive to match the style of the rest of the Froala icons. The icon is from a free icons website and doesn’t require attribution.

Setting Up the Froala Google Drive Plugin

Place the following code inside a file that is included on the page along with the rest of the plugins you use (such as the file upload plugin). You can call it froala_google_drive_plugin.js:

$.FroalaEditor.DefineIcon('googleDriveIcon', {
    SRC: '/some/path/google_drive_bw.png',
    ALT: 'Google Drive', template: 'image'

$.FroalaEditor.RegisterCommand('googleDriveUpload', {
    title: 'Insert File From Google Drive',
    icon: 'googleDriveIcon',
    focus: false,
    undo: false,
    refreshAfterCallback: false,
    callback: function () {
        util.saveFroalaUserPlace(); // will be covered down below

The above code registers an icon, then registers a Froala button that uses the icon. The callback function does nothing besides storing the user’s place in the editor (or the user’s selection, if they have selected any text right before clicking the Google Drive icon), otherwise their place will be lost once we insert the file, and the file would end up at the bottom of the editor. The user’s place in the editor is saved as a Range object. This will be covered down below.

Getting the Google Drive icon to show up

On the page where you have the Froala editor, your Froala initialization code may look something like this:

var froala_buttons = ['bold', 'italic', ...];
var froala_options = {
toolbarButtons: froala_buttons


To get the Google Drive icon to show up, add its command name to the buttons array. The command name is whatever name you used as the first argument to the RegisterCommand() function above.

var froala_buttons = ['bold', 'italic', ... , 'googleDriveUpload', ...];

A new way to initialize Froala

Above, I showed the usual way of initializing Froala:


That will have to be changed to this:

$('#froala_editor_container').on('froalaEditor.initialized', function (e, editor) {

Here we attach an event listener to the Froala container that is called as soon as Froala is done initializing. The event listener calls a custom function util.initFroalaGoogleDriveUpload(editor) that will set up the Google Drive buttons functionality. We pass the function the editor object. This is the Froala object, giving us access to the editor and its options, which we will use for various purposes. By using the editor object, we are able to handle having multiple Froala editors on the same page without issue, being able to insert files and images into the correct editor.

The Google Drive initialization function

Below is the function that is called when Froala loads, it binds a bunch of functionality to the Google Drive button.

window.util = {
    initFroalaGoogleDriveUpload: function (editor) {
        // get the icon object from the editor using jQuery find()
        var icon_el = editor.$box.find('[id^=googleDrive]')[0];

        // add a class to the button, to use for styling

        // get the URL to use to handle the upload, here we use the same URL
        // as the one used by the file upload plugin
        var upload_handler_url = editor.opts.fileUploadURL;

        // The function that is called right after a user selects a file in the Google Drive picker
        var pick_callback = function (file) {
            util.storeGoogleDriveFileOnServer(file, upload_handler_url, util.froalaAjaxCallback, editor); // covered down below

        util.initGoogleDrivePicker(icon_el, pick_callback); // covered down below

Handling the Google Client

Please see my blog post A guide to using PHP to download Google Drive files selected by users in the Google Drive Picker for an overview of how the Google Drive picker works. Here I will use the same methods with some changes.

Since the binding of the Google Drive icon to the Google library has to be done after the library has loaded, the library is included in this way:

function googleClientHasLoaded() {
    util.google_client_loaded = true;

<script src="https://apis.google.com/js/client.js?onload=googleClientHasLoaded">

The util.initGoogleDrivePicker() function

This function is called once, soon after page load, to bind the Google Drive picker library to the Froala icon. It uses a timeout to detect if the Google library has loaded. If not, it waits 500 milliseconds and tries again.

The callback is the pick_callback() function that was defined in util.initFroalaGoogleDriveUpload() above. When a user selects a file in the Google Drive picker, the onSelect() function is called, which extracts information from the file object, creates a new object from it, and passes that object to pick_callback().

window.util = {
google_client_loaded = false,

// I use the library at https://gist.github.com/Daniel15/5994054
// to interface with the Google Drive Picker.
initGoogleDrivePicker: function (button_el, callback) {
        if (!util.google_client_loaded) {
            setTimeout(function () {
                util.initGoogleDrivePicker(button_el, callback);
            }, 500);
        var picker = new FilePicker({
            apiKey: api_key,
            clientId: client_id,
            buttonEl: button_el,
            onSelect: function (file) {
                        id: file.id,
                        name: file.title,
                        extension: file.fileExtension,
                        mime_type: file.mimeType,
                        access_token: gapi.auth.getToken().access_token,

Storing the file on the server

As you remember, or perhaps don’t, the pick_callback() function is as below:

var pick_callback = function (file) {
    util.storeGoogleDriveFileOnServer(file, upload_handler_url, util.froalaAjaxCallback, editor); 

The util.storeGoogleDriveFileOnServer() function is as below. It sends the file’s information to the server, the server stores the file (see the blog post I linked above for the details of storing the file). The server echoes out the download URL of the file, the link that users can go to to download the file. That download url, along with the file object and the editor, are passed to the callback. The callback is util.froalaAjaxCallback(), mentioned above in the pick_callback() function and covered down below.

    storeGoogleDriveFileOnServer: function (file, handler_url, callback, editor) {
        var data = {
            file: file,
            command: 'store-google-drive-file',

            url: handler_url,
            type: 'post',
            data: data,
            error: function (data) {
            success: function (download_url) {
                    callback(file, download_url, editor);

Inserting the image or link into Froala with util.froalaAjaxCallback()

At this point, the Google Drive file is stored on our local server and we have a link to it that users can go to download the file. Now we need to insert that link into the editor.

    froalaAjaxCallback: function (file, path, editor) {
        // restore the user's place in the editor, covered down below

        // if the user has selected some text in the editor, insert a link to the file
        // and make the selected text the link text
        if (editor.selection.text().length) {
            var link_text = editor.selection.text();
        else {
            var link_text = file.name;

        // if the file has an image extension in its link, insert the file as an image
        if (/[.](png|jpg|gif|jpeg|svg)/.test(path)) {
            // if user has selected text in the editor, preserve the text, otherwise it will be
            // overwritten by the image
            if (editor.selection.text().length) {
                editor.html.insert(editor.selection.text() + '<img id="fr-inserted-file" class="fr-image" src="' + path + '" />');
            else {
                editor.html.insert('<img id="fr-inserted-file" class="fr-image" src="' + path + '" />');
        else { // if not an image, insert a link to the file
            editor.html.insert('<a id="fr-inserted-file" class="fr-file" href="' + path + '">' + link_text + '</a>');

        // Get the file.
        var $file = editor.$el.find('#fr-inserted-file');



On saving and restoring the user’s place in the editor

Below is the code used to save and restore a user’s place in the editor, and any text they may have selected, as the Google Drive picker will make them lose their place/selection. The getSelection() and restoreSelection() functions are from a StackOverflow answer.

window.util {
        froala_user_place = false;
        saveFroalaUserPlace() {
            util.froala_user_place = util.getSelection();

        restoreFroalaUserPlace() {

        getSelection: function () {
            if (window.getSelection) {
                sel = window.getSelection();
                if (sel.getRangeAt && sel.rangeCount) {
                    return sel.getRangeAt(0);
            } else if (document.selection && document.selection.createRange) {
                return document.selection.createRange();
            return null;

        restoreSelection: function (range) {
            if (range) {
                if (window.getSelection) {
                    sel = window.getSelection();
                } else if (document.selection && range.select) {


The above solution should be easy to extend to support OneDrive as well. See these two guides of mine if you need help with the OneDrive picker: How to get a demo of the OneDrive File Picker JavaScript SDK to work on a local development server, A guide to using PHP to download OneDrive files selected by users in the OneDrive Picker.


I think that’s it. Some of the code above is from memory, so it may not compile. I throw everything into the util object for demo purposes, in my actual setup things are separated out into different objects and files.

The Point

The point is that there is no point.
The stars will burn out.
Our deeds will turn to dust.
Our names will be forgotten.
And the names of our children.
And the names of their children.
And the names of all humans that ever lived.

And the Earth will join the Sun.
Joined in the dark, in a darkening galaxy.

All will be darkness.
There will be no sound. 
No movement. No light.
Darkness everywhere.
Darkness all around.

The point is that there is no point.
There is no need to worry about success.
There is no need to worry about where your life is going.
It is not going anywhere.

Soon, there will be no “where” for it to go to.

The point is that there is no point.
Empty are our words,
Empty are our deeds.
Our lives are going nowhere.

This is what life feels like to me without God—if there is no God to preserve our genes and deeds and resurrect us at some point in the future. Written on May 27, 2016. Also a reminder of the emptiness of all deeds and accomplishments other than those that benefit the afterlife.

/ No Comments on The Point

A guide to using PHP to download OneDrive files selected by users in the OneDrive Picker

In my previous blog post  I described how to get the OneDrive picker to work on a local development server. In this post I will describe the second piece of the puzzle, downloading the file to a local server using PHP after the user selects it:

First, below is the JavaScript/jQuery used to open the file picker:

$(function() {
    $('.onedrive-button').click(function() {

function openOneDrivePicker() {
    var odOptions = {
        clientId: client_id,
        action: "download",
        advanced: {
            redirectUri: redirect_uri,
        multiSelect: true,
        openInNewWindow: true,
        success: function (files) { /* success handler */
            var files_array = files.value;
            for(var i in files_array) {
        cancel: function () { /* cancel handler */
        error: function (e) { /* error handler */

The success method goes through the file or files selected and calls a function called processOneDriveFile() on each one of the file objects.

Below is the code to the processOneDriveFile() function, which submits the file to a PHP handler file called file_handler.php:

// this function automatically submits the file to the server as soon
// as the user picks a file from the OneDrive picker. You may
// instead want to store the files in a variable and only submit when
// the user clicks some "Submit" button somewhere in your app.
function processOneDriveFile(file) {
    var file_name = file.name;
    var file_size = file.size;
    var download_url = file['@microsoft.graph.downloadUrl'];

    var data = {
        file_name : file_name,
        file_size : file_size,
        download_url : download_url,
        command : 'handle-onedrive-file',
        url: '/path/to/file_handler.php',
        type: 'post',
        data: data,
        error: function (data) {
        success: function (data) {
            // success message

And here is the code for file_handler.php:

// bootstrap code

$command = $_POST['command'];

if('handle-onedrive-file' === $command) {
 $file_name = $_POST['file_name'];
 $file_size = $_POST['file_size'];
 $download_url = $_POST['download_url'];

 $ch = curl_init($download_url);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);

 $data = curl_exec($ch);
 $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
 $error = curl_errno($ch);
 // A file with the same name may exist, that must be handled.
 $file_save_path = '/some/path/' . $file_name;

 file_put_contents($file_save_path, $data);
 echo 'File successfully retrieved and stored!';

That’s all. Make sure that the curl PHP library is installed and enabled (it is not sufficient to have the Linux curl utility, the code above uses the PHP library for it).

A guide to using PHP to download Google Drive files selected by users in the Google Drive Picker

Let’s say you’ve managed to get the Google Drive JavaScript Picker API to work, and have also managed to coerce your users into logging into the Picker and selecting one of their files:

And you have verified that the onSelect function works properly:

function initGoogleDrivePicker() {
    var picker = new FilePicker({
        apiKey: api_key,
        clientId: client_id,
        buttonEl: document.getElementsByClassName('google-drive-button')[0],
        onSelect: function (file) {

Where to go from here to send the file to the server and have it saved there?

First, we’ll create a function called processGoogleDriveFile(file), which will be added to the onSelect function of the picker:

function initGoogleDrivePicker() {
    var picker = new FilePicker({
        apiKey: api_key,
        clientId: client_id,
        buttonEl: document.getElementsByClassName('google-drive-button')[0],
        onSelect: function (file) {

The function will be as follows. It will extract the file’s information, then use a jQuery AJAX request to send it to a PHP file called file_handler.php:

// this function automatically submits the file to the server as soon
// as the user picks a file from the Google Drive picker. You may
// instead want to store the files in a variable and only submit when
// the user clicks some "Submit" button somewhere in your app.
function processGoogleDriveFile(file) {
    var data = {
        file_id : file.id,
        file_name : file.title,
        extension: file.fileExtension,
        mime_type : file.mimeType,
        // the function below is provided by the library
        // from https://gist.github.com/Daniel15/5994054
        access_token : gapi.auth.getToken().access_token,
        command : 'handle-google-drive-file',
        url: '/path/to/file_handler.php',
        type: 'post',
        data: data,
        error: function (data) {
        success: function (data) {
            // success message

On the back-end side, in file_handler.php, we have the following code:

// bootstrap code

$command = $_POST['command'];

if('handle-google-drive-file' === $command) {
    $file_id = $_POST['file_id'];
    $file_name = $_POST['file_name'];
    $extension = $_POST['extension'];
    $mime_type = $_POST['mime_type'];
    $access_token = $_POST['access_token'];
    // if this is a Google Docs file type (Google Docs, 
    // Spreadsheets, Presentations, etc.) we convert it
    // to a PDF using the export function of the API before saving it.
    // we could convert it to other file types that are also supported
    // by the API.
    if (stripos($mime_type, 'google')) {
        $getUrl = 'https://www.googleapis.com/drive/v2/files/' . $file_id .
        $authHeader = 'Authorization: Bearer ' . $access_token;
        $file_name = $file_name . " (converted)";
        $extension = 'pdf';
        $file_mime_type = 'application/pdf';
    else { // otherwise we download it the normal way
        $getUrl = 'https://www.googleapis.com/drive/v2/files/' . $file_id . 
        $authHeader = 'Authorization: Bearer ' . $access_token;

    $ch = curl_init($getUrl);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [$authHeader]);

    $data = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_errno($ch);

    // 1. the file name could already have an extension in some cases,
    // that must be handled if needed.
    // 2. A file with the same name may exist, that must be handled.
    $file_save_path = '/some/path/' . $file_name . '.' . $extension;

    file_put_contents($file_save_path, $data);
    echo 'File successfully retrieved and stored!';

That’s all that is needed. Not all of Google’s proprietary MIME types can be converted to PDF. You must add a check to the onSelect or processGoogleDriveFile() JavaScript functions to check whether this is a MIME type you want to support. If it not, you can alert the user to choose another file.

Make sure that the curl PHP library is installed and enabled (it is not sufficient to have the Linux curl utility, the code above uses the PHP library for it).