simplenews.test 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949
  1. <?php
  2. /**
  3. * @file
  4. * Simplenews test functions.
  5. *
  6. * @ingroup simplenews
  7. */
  8. class SimplenewsTestCase extends DrupalWebTestCase {
  9. // Use testing profile to speed up tests.
  10. protected $profile = 'testing';
  11. // Store generated email addresses used to prevent duplications.
  12. protected $mailadress_cache;
  13. public function setUp($modules = array()) {
  14. $modules = array_merge(array('taxonomy', 'simplenews'), $modules);
  15. parent::setUp($modules);
  16. //$this->simplenews_admin_user = $this->drupalCreateUser(array('administer newsletters', 'administer simplenews settings', 'administer simplenews subscriptions'));
  17. //$this->sender_user = $this->drupalCreateUser(array('create simplenews content', 'edit own simplenews content', 'send newsletter'));
  18. variable_set('site_mail', 'user@example.com');
  19. $this->mailadress_cache = array();
  20. }
  21. /**
  22. * Set anonymous user permission to subscribe.
  23. *
  24. * @param boolean $enabled
  25. * Allow anonymous subscribing.
  26. */
  27. function setAnonymousUserSubscription($enabled) {
  28. if ($enabled) {
  29. db_insert('role_permission')
  30. ->fields(array('rid', 'permission'), array(DRUPAL_ANONYMOUS_RID, 'subscribe to newsletters'))
  31. ->execute();
  32. }
  33. }
  34. /**
  35. * Set authenticated user permission to subscribe.
  36. *
  37. * @param boolean $enabled
  38. * Allow authenticated subscribing.
  39. */
  40. function setAuthenticatedUserSubscription($enabled) {
  41. if ($enabled) {
  42. db_insert('role_permission')
  43. ->fields(array('rid', 'permission'), array(DRUPAL_AUTHENTICATED_RID, 'subscribe to newsletters'))
  44. ->execute();
  45. }
  46. }
  47. /**
  48. * Generates a random email address.
  49. *
  50. * The generated addresses are stored in a class variable. Each generated
  51. * adress is checked against this store to prevent duplicates.
  52. *
  53. * @todo: Make this function redundant by modification of Simplenews.
  54. * Email addresses are case sensitive, simplenews system should handle with
  55. * this correctly.
  56. */
  57. function randomEmail($number = 4, $prefix = 'simpletest_', $domain = 'example.com') {
  58. $mail = '';
  59. do {
  60. $mail = drupal_strtolower($this->randomName($number, $prefix) . '@' . $domain);
  61. } while (in_array($mail, $this->mailadress_cache));
  62. $this->mailadress_cache[] = $mail;
  63. return $mail;
  64. }
  65. /**
  66. * Select randomly one of the available newsletters.
  67. *
  68. * @return newsletter tid.
  69. */
  70. function getRandomNewsletter() {
  71. $vid = db_query('SELECT vid FROM {taxonomy_vocabulary} WHERE machine_name = :name', array(':name' => 'newsletter'))->fetchField();
  72. if ($taxonomies = taxonomy_get_tree($vid)) {
  73. $tids = array();
  74. foreach ($taxonomies as $newsletter) {
  75. $tids[] = $newsletter->tid;
  76. }
  77. $key = array_rand($tids);
  78. return $tids[$key];
  79. }
  80. return 0;
  81. }
  82. /**
  83. * Enable newsletter subscription block.
  84. *
  85. * @param integer $tid
  86. * newsletter term id
  87. * @param array $settings
  88. * ['message'] = Block message
  89. * ['form'] = '1': Subscription form; '0': Link to form
  90. * ['link to previous'] = {1, 0} Display link to previous issues
  91. * ['previous issues'] = {1, 0} Display previous issues
  92. * ['issue count'] = {1, 2, 3, ...}Number of issues to display
  93. * ['rss feed'] = {1, 0} Display RSS-feed icon
  94. */
  95. function setupSubscriptionBlock($tid, $settings = array()) {
  96. $bid = db_select('block')
  97. ->fields('block', array('bid'))
  98. ->condition('module', 'simplenews')
  99. ->condition('delta', $tid)
  100. ->execute();
  101. // Check to see if the box was created by checking that it's in the database..
  102. $this->assertNotNull($bid, t('Block found in database'));
  103. // Set block parameters
  104. $edit = array();
  105. $edit['regions[bartik]'] = 'sidebar_first';
  106. if (isset($settings['message'])) {
  107. $edit['simplenews_block_m_' . $tid] = $settings['message'];
  108. }
  109. if (isset($settings['form'])) {
  110. $edit['simplenews_block_f_' . $tid] = $settings['form'];
  111. }
  112. if (isset($settings['link to previous'])) {
  113. $edit['simplenews_block_l_' . $tid] = $settings['link to previous'];
  114. }
  115. if (isset($settings['previous issues'])) {
  116. $edit['simplenews_block_i_status_' . $tid] = $settings['previous issues'];
  117. }
  118. if (isset($settings['issue count'])) {
  119. $edit['simplenews_block_i_' . $tid] = $settings['issue count'];
  120. // @todo check the count
  121. }
  122. if (isset($settings['rss feed'])) {
  123. $edit['simplenews_block_r_' . $tid] = $settings['rss feed'];
  124. }
  125. // Simplify confirmation form submission by hiding the subscribe block on
  126. // that page. Same for the newsletter/subscriptions page.
  127. $edit['pages'] = "newsletter/confirm/*\nnewsletter/subscriptions";
  128. $this->drupalPost('admin/structure/block/manage/simplenews/' . $tid . '/configure', $edit, t('Save block'));
  129. $this->assertText('The block configuration has been saved.', 'The newsletter block configuration has been saved.');
  130. }
  131. function setUpSubscribers($count = 100, $tid = 1) {
  132. // Subscribe users.
  133. $this->subscribers = array();
  134. for ($i = 0; $i < $count; $i++) {
  135. $mail = $this->randomEmail();
  136. $this->subscribers[$mail] = $mail;
  137. }
  138. $this->drupalGet('admin/people/simplenews');
  139. $this->clickLink(t('Mass subscribe'));
  140. $edit = array(
  141. 'emails' => implode(',', $this->subscribers),
  142. // @todo: Don't hardcode the default tid.
  143. 'newsletters[' . $tid . ']' => TRUE,
  144. );
  145. $this->drupalPost(NULL, $edit, t('Subscribe'));
  146. }
  147. }
  148. class SimplenewsSubscribeTestCase extends SimplenewsTestCase {
  149. /**
  150. * Implement getInfo().
  151. */
  152. function getInfo() {
  153. return array(
  154. 'name' => t('Subscribe and unsubscribe users'),
  155. 'description' => t('(un)subscription of anonymous and authenticated users. Subscription via block, subscription page and account page'),
  156. 'group' => t('Simplenews'),
  157. );
  158. }
  159. /**
  160. * Overrides SimplenewsTestCase::setUp().
  161. */
  162. public function setUp() {
  163. parent::setUp(array('block'));
  164. // Include simplenews.subscription.inc for simplenews_mask_mail().
  165. module_load_include('inc', 'simplenews', 'includes/simplenews.subscription');
  166. }
  167. /**
  168. * Subscribe to multiple newsletters at the same time.
  169. */
  170. function testSubscribeMultiple() {
  171. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer content types', 'administer nodes', 'access administration pages', 'administer permissions', 'administer newsletters'));
  172. $this->drupalLogin($admin_user);
  173. $this->setAnonymousUserSubscription(TRUE);
  174. $this->drupalGet('admin/config/services/simplenews');
  175. for ($i = 0; $i < 5; $i++) {
  176. $this->clickLink(t('Add newsletter category'));
  177. $edit = array(
  178. 'name' => $this->randomName(),
  179. 'description' => $this->randomString(20),
  180. 'opt_inout' => 'double',
  181. );
  182. $this->drupalPost(NULL, $edit, t('Save'));
  183. }
  184. drupal_static_reset('simplenews_categories_load_multiple');
  185. $categories = simplenews_categories_load_multiple();
  186. $this->drupalLogout();
  187. $enable = array_rand($categories, 3);
  188. $mail = $this->randomEmail(8, 'testmail');
  189. $edit = array(
  190. 'mail' => $mail,
  191. );
  192. foreach ($enable as $tid) {
  193. $edit['newsletters[' . $tid . ']'] = TRUE;
  194. }
  195. $this->drupalPost('newsletter/subscriptions', $edit, t('Subscribe'));
  196. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'), t('Subscription confirmation e-mail sent.'));
  197. $mails = $this->drupalGetMails();
  198. $body = $mails[0]['body'];
  199. // Verify listed changes.
  200. foreach ($categories as $tid => $category) {
  201. $pos = strpos($body, t('Subscribe to @name', array('@name' => $category->name)));
  202. if (in_array($tid, $enable)) {
  203. $this->assertTrue($pos);
  204. }
  205. else {
  206. $this->assertFalse($pos);
  207. }
  208. }
  209. $pattern = '@newsletter/confirm/combined/[0-9,a-f]+t0@';
  210. $found = preg_match($pattern, $body, $match);
  211. $confirm_url = $match[0];
  212. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  213. $this->drupalGet($confirm_url);
  214. $this->assertRaw(t('Are you sure you want to confirm the following subscription changes for %user?', array('%user' => simplenews_mask_mail($mail))), t('Subscription confirmation found.'));
  215. // Verify listed changes.
  216. foreach ($categories as $tid => $category) {
  217. if (in_array($tid, $enable)) {
  218. $this->assertText(t('Subscribe to @name', array('@name' => $category->name)));
  219. }
  220. else {
  221. $this->assertNoText(t('Subscribe to @name', array('@name' => $category->name)));
  222. }
  223. }
  224. $this->drupalPost($confirm_url, NULL, t('Confirm'));
  225. $this->assertRaw(t('Subscription changes confirmed for %user.', array('%user' => $mail)), t('Anonymous subscriber added to newsletter'));
  226. // Verify subscription changes.
  227. foreach ($categories as $tid => $category) {
  228. $is_subscribed = simplenews_user_is_subscribed($mail, $tid);
  229. if (in_array($tid, $enable)) {
  230. $this->assertTrue($is_subscribed);
  231. }
  232. else {
  233. $this->assertFalse($is_subscribed);
  234. }
  235. }
  236. // Go to the manage page and submit without changes.
  237. $subscriber = simplenews_subscriber_load_by_mail($mail);
  238. $hash = simplenews_generate_hash($subscriber->mail, $subscriber->snid, $tid);
  239. $this->drupalPost('newsletter/subscriptions/' . $hash, array(), t('Update'));
  240. $mails = $this->drupalGetMails();
  241. $body = $mails[1]['body'];
  242. $this->assertTrue(strpos($body, 'No confirmation necessary'));
  243. $pattern = '@newsletter/confirm/combined/[0-9,a-f]+t0@';
  244. $found = preg_match($pattern, $body, $match);
  245. $this->assertFalse($found, t('No confirmation link in unchanged confirm mail.'));
  246. // Unsubscribe from two of the three enabled newsletters.
  247. $disable = array_rand(array_flip($enable), 2);
  248. $edit = array(
  249. 'mail' => $mail,
  250. );
  251. foreach ($disable as $tid) {
  252. $edit['newsletters[' . $tid . ']'] = TRUE;
  253. }
  254. $this->drupalPost('newsletter/subscriptions', $edit, t('Unsubscribe'));
  255. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to cancel your subscription.'), t('Subscription confirmation e-mail sent.'));
  256. $mails = $this->drupalGetMails();
  257. $body = $mails[2]['body'];
  258. // Verify listed changes.
  259. foreach ($categories as $tid => $category) {
  260. $pos = strpos($body, t('Unsubscribe from @name', array('@name' => $category->name)));
  261. if (in_array($tid, $disable)) {
  262. $this->assertTrue($pos);
  263. }
  264. else {
  265. $this->assertFalse($pos);
  266. }
  267. }
  268. $pattern = '@newsletter/confirm/combined/[0-9,a-f]+t0@';
  269. $found = preg_match($pattern, $body, $match);
  270. $confirm_url = $match[0];
  271. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  272. $this->drupalGet($confirm_url);
  273. $this->assertRaw(t('Are you sure you want to confirm the following subscription changes for %user?', array('%user' => simplenews_mask_mail($mail))), t('Subscription confirmation found.'));
  274. // Verify listed changes.
  275. foreach ($categories as $tid => $category) {
  276. if (in_array($tid, $disable)) {
  277. $this->assertText(t('Unsubscribe from @name', array('@name' => $category->name)));
  278. }
  279. else {
  280. $this->assertNoText(t('Unsubscribe from @name', array('@name' => $category->name)));
  281. }
  282. }
  283. $this->drupalPost($confirm_url, NULL, t('Confirm'));
  284. $this->assertRaw(t('Subscription changes confirmed for %user.', array('%user' => $mail)), t('Anonymous subscriber added to newsletter'));
  285. // Verify subscription changes.
  286. drupal_static_reset('simplenews_user_is_subscribed');
  287. $still_enabled = array_diff($enable, $disable);
  288. foreach ($categories as $tid => $category) {
  289. $is_subscribed = simplenews_user_is_subscribed($mail, $tid);
  290. if (in_array($tid, $still_enabled)) {
  291. $this->assertTrue($is_subscribed);
  292. }
  293. else {
  294. $this->assertFalse($is_subscribed);
  295. }
  296. }
  297. // Make sure that a single change results in a non-multi confirmation mail.
  298. $tid = reset($disable);
  299. $edit = array(
  300. 'mail' => $mail,
  301. 'newsletters[' . $tid . ']' => TRUE,
  302. );
  303. $this->drupalPost('newsletter/subscriptions', $edit, t('Subscribe'));
  304. $mails = $this->drupalGetMails();
  305. $body = $mails[3]['body'];
  306. $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
  307. $found = preg_match($pattern, $body, $match);
  308. $confirm_url = $match[0];
  309. $this->assertTrue($found, t('Single add confirmation URL found: @url', array('@url' => $confirm_url)));
  310. // Change behavior to always use combined mails.
  311. variable_set('simplenews_use_combined', 'always');
  312. $edit = array(
  313. 'mail' => $mail,
  314. 'newsletters[' . $tid . ']' => TRUE,
  315. );
  316. $this->drupalPost('newsletter/subscriptions', $edit, t('Subscribe'));
  317. $mails = $this->drupalGetMails();
  318. $body = $mails[4]['body'];
  319. $pattern = '@newsletter/confirm/combined/[0-9,a-f]+t0@';
  320. $found = preg_match($pattern, $body, $match);
  321. $confirm_url = $match[0];
  322. $this->assertTrue($found, t('Multi confirmation URL found: @url', array('@url' => $confirm_url)));
  323. // Change behavior to never, should send two separate mails.
  324. variable_set('simplenews_use_combined', 'never');
  325. $edit = array(
  326. 'mail' => $mail,
  327. );
  328. foreach ($disable as $tid) {
  329. $edit['newsletters[' . $tid . ']'] = TRUE;
  330. }
  331. $this->drupalPost('newsletter/subscriptions', $edit, t('Subscribe'));
  332. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'), t('Subscription confirmation e-mail sent.'));
  333. $mails = $this->drupalGetMails();
  334. foreach (array(5, 6) as $id) {
  335. $body = $mails[$id]['body'];
  336. $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
  337. $found = preg_match($pattern, $body, $match);
  338. $confirm_url = $match[0];
  339. $this->assertTrue($found, t('Single add confirmation URL found: @url', array('@url' => $confirm_url)));
  340. }
  341. // Make sure that the /ok suffix works, subscribe from everything.
  342. variable_del('simplenews_use_combined');
  343. $edit = array(
  344. 'mail' => $mail,
  345. );
  346. foreach (array_keys($categories) as $tid) {
  347. $edit['newsletters[' . $tid . ']'] = TRUE;
  348. }
  349. $this->drupalPost('newsletter/subscriptions', $edit, t('Unsubscribe'));
  350. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to cancel your subscription.'));
  351. $mails = $this->drupalGetMails();
  352. $body = $mails[7]['body'];
  353. $pattern = '@newsletter/confirm/combined/[0-9,a-f]+t0@';
  354. $found = preg_match($pattern, $body, $match);
  355. $confirm_url = $match[0];
  356. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  357. $this->drupalGet($confirm_url . '/ok');
  358. $this->assertRaw(t('Subscription changes confirmed for %user.', array('%user' => $mail)), t('Confirmation message displayed.'));
  359. // Verify subscription changes.
  360. drupal_static_reset('simplenews_user_is_subscribed');
  361. foreach (array_keys($categories) as $tid) {
  362. $this->assertFalse(simplenews_user_is_subscribed($mail, $tid));
  363. }
  364. // Call confirmation url after it is allready used.
  365. // Using direct url.
  366. $this->drupalGet($confirm_url . '/ok');
  367. $this->assertNoResponse(404, 'Redirected after calling confirmation url more than once.');
  368. $this->assertRaw(t('All changes to your subscriptions where already applied. No changes made.'));
  369. // Using confirmation page.
  370. $this->drupalGet($confirm_url);
  371. $this->assertNoResponse(404, 'Redirected after calling confirmation url more than once.');
  372. $this->assertRaw(t('All changes to your subscriptions where already applied. No changes made.'));
  373. }
  374. /**
  375. * testSubscribeAnonymous
  376. *
  377. * Steps performed:
  378. * 0. Preparation
  379. * 1. Subscribe anonymous via block
  380. * 2. Subscribe anonymous via subscription page
  381. * 3. Subscribe anonymous via multi block
  382. */
  383. function testSubscribeAnonymous() {
  384. // 0. Preparation
  385. // Login admin
  386. // Set permission for anonymous to subscribe
  387. // Enable newsletter block
  388. // Logout admin
  389. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer content types', 'administer nodes', 'access administration pages', 'administer permissions'));
  390. $this->drupalLogin($admin_user);
  391. $this->setAnonymousUserSubscription(TRUE);
  392. // Setup subscription block with subscription form.
  393. $block_settings = array(
  394. 'message' => $this->randomName(4),
  395. 'form' => '1',
  396. 'link to previous' => FALSE,
  397. 'previous issues' => FALSE,
  398. 'rss feed' => TRUE,
  399. );
  400. $tid = $this->getRandomNewsletter();
  401. $this->setupSubscriptionBlock($tid, $block_settings);
  402. $this->drupalLogout();
  403. //file_put_contents('output.html', $this->drupalGetContent());
  404. // 1. Subscribe anonymous via block
  405. // Subscribe + submit
  406. // Assert confirmation message
  407. // Assert outgoing email
  408. //
  409. // Confirm using mail link
  410. // Confirm using mail link
  411. // Assert confirmation message
  412. $mail = $this->randomEmail(8, 'testmail');
  413. $edit = array(
  414. 'mail' => $mail,
  415. );
  416. $this->drupalPost(NULL, $edit, t('Subscribe'));
  417. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'), t('Subscription confirmation e-mail sent.'));
  418. $subscriber = simplenews_subscriber_load_by_mail($mail);
  419. $subscription = db_query('SELECT * FROM {simplenews_subscription} WHERE snid = :snid AND tid = :tid', array(':snid' => $subscriber->snid, ':tid' => $tid))->fetchObject();
  420. $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_UNCONFIRMED, $subscription->status, t('Subscription is unconfirmed'));
  421. $mails = $this->drupalGetMails();
  422. $body = $mails[0]['body'];
  423. $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
  424. preg_match($pattern, $body, $match);
  425. $found = preg_match($pattern, $body, $match);
  426. $confirm_url = $match[0];
  427. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  428. $this->drupalGet($confirm_url);
  429. $newsletter = taxonomy_term_load($tid);
  430. $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
  431. $this->drupalPost(NULL, array(), t('Subscribe'));
  432. $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
  433. // Test that it is possible to register with a mail address that is already
  434. // a subscriber.
  435. variable_set('user_register', 1);
  436. variable_set('user_email_verification', FALSE);
  437. $edit = array(
  438. 'name' => $this->randomName(),
  439. 'mail' => $mail,
  440. 'pass[pass1]' => $pass = $this->randomName(),
  441. 'pass[pass2]' => $pass,
  442. );
  443. $this->drupalPost('user/register', $edit, t('Create new account'));
  444. // Verify confirmation messages.
  445. $this->assertText(t('Registration successful. You are now logged in.'));
  446. // Verify that the subscriber has been updated and references to the correct
  447. // user.
  448. $subscriber = simplenews_subscriber_load_by_mail($mail);
  449. $account = user_load_by_mail($mail);
  450. $this->assertEqual($subscriber->uid, $account->uid);
  451. $this->assertEqual($account->name, $edit['name']);
  452. $this->drupalLogout();
  453. // 2. Subscribe anonymous via subscription page
  454. // Subscribe + submit
  455. // Assert confirmation message
  456. // Assert outgoing email
  457. //
  458. // Confirm using mail link
  459. // Confirm using mail link
  460. // Assert confirmation message
  461. $mail = $this->randomEmail(8, 'testmail');
  462. $edit = array(
  463. "newsletters[$tid]" => '1',
  464. 'mail' => $mail,
  465. );
  466. $this->drupalPost('newsletter/subscriptions', $edit, t('Subscribe'));
  467. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'), t('Subscription confirmation e-mail sent.'));
  468. $mails = $this->drupalGetMails();
  469. $body = $mails[2]['body'];
  470. $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
  471. preg_match($pattern, $body, $match);
  472. $found = preg_match($pattern, $body, $match);
  473. $confirm_url = $match[0];
  474. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  475. $this->drupalGet($confirm_url);
  476. $newsletter = taxonomy_term_load($tid);
  477. $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
  478. $this->drupalPost($confirm_url, NULL, t('Subscribe'));
  479. $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
  480. // 3. Subscribe anonymous via multi block
  481. $this->drupalLogin($admin_user);
  482. // Enable the multi-sign up block.
  483. $this->setupSubscriptionBlock(0);
  484. // Disable the category block.
  485. $edit = array(
  486. 'blocks[simplenews_' . $tid . '][region]' => -1,
  487. );
  488. $this->drupalPost(NULL, $edit, t('Save blocks'));
  489. $this->drupalLogout();
  490. // Try to submit multi-signup form without selecting a category.
  491. $mail = $this->randomEmail(8, 'testmail');
  492. $edit = array(
  493. 'mail' => $mail,
  494. );
  495. $this->drupalPost(NULL, $edit, t('Subscribe'));
  496. $this->assertText(t('You must select at least one newsletter.'));
  497. // Now fill out the form and try again. The e-mail should still be listed.
  498. $edit = array(
  499. 'newsletters[' . $tid . ']' => TRUE,
  500. );
  501. $this->drupalPost(NULL, $edit, t('Subscribe'));
  502. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'));
  503. $mails = $this->drupalGetMails();
  504. $body = $mails[3]['body'];
  505. $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
  506. preg_match($pattern, $body, $match);
  507. $found = preg_match($pattern, $body, $match);
  508. $confirm_url = $match[0];
  509. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  510. $this->drupalGet($confirm_url);
  511. $newsletter = taxonomy_term_load($tid);
  512. $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
  513. $this->drupalPost($confirm_url, NULL, t('Subscribe'));
  514. $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
  515. // Try to subscribe again, this should not re-set the status to unconfirmed.
  516. $edit = array(
  517. 'mail' => $mail,
  518. 'newsletters[' . $tid . ']' => TRUE,
  519. );
  520. $this->drupalPost(NULL, $edit, t('Subscribe'));
  521. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'));
  522. $subscriber = simplenews_subscriber_load_by_mail($mail);
  523. $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED, $subscriber->newsletter_subscription[$tid]->status);
  524. // Now the same with the newsletter/subscriptions page.
  525. $mail = $this->randomEmail(8, 'testmail');
  526. $edit = array(
  527. 'mail' => $mail,
  528. );
  529. $this->drupalPost('newsletter/subscriptions', $edit, t('Subscribe'));
  530. $this->assertText(t('You must select at least one newsletter.'));
  531. // Now fill out the form and try again.
  532. $edit = array(
  533. 'newsletters[' . $tid . ']' => TRUE,
  534. );
  535. $this->drupalPost(NULL, $edit, t('Subscribe'));
  536. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.'));
  537. $mails = $this->drupalGetMails();
  538. $body = $mails[5]['body'];
  539. $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
  540. $found = preg_match($pattern, $body, $match);
  541. $confirm_url = $match[0];
  542. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  543. $this->drupalGet($confirm_url);
  544. $newsletter = taxonomy_term_load($tid);
  545. $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
  546. $this->drupalPost($confirm_url, NULL, t('Subscribe'));
  547. $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
  548. // Test unsubscribe on newsletter/subscriptions page.
  549. $edit = array(
  550. 'mail' => $mail,
  551. );
  552. $this->drupalPost('newsletter/subscriptions', $edit, t('Unsubscribe'));
  553. $this->assertText(t('You must select at least one newsletter.'));
  554. // Now fill out the form and try again.
  555. $edit = array(
  556. 'newsletters[' . $tid . ']' => TRUE,
  557. );
  558. $this->drupalPost(NULL, $edit, t('Unsubscribe'));
  559. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to cancel your subscription.'));
  560. $mails = $this->drupalGetMails();
  561. $body = $mails[6]['body'];
  562. $this->assertTrue(strpos($body, t('We have received a request to remove the @mail', array('@mail' => $mail))) === 0);
  563. $pattern = '@newsletter/confirm/remove/[0-9,a-f]+t[0-9]+@';
  564. $found = preg_match($pattern, $body, $match);
  565. $confirm_url = $match[0];
  566. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  567. $this->drupalGet($confirm_url);
  568. $newsletter = taxonomy_term_load($tid);
  569. $this->assertRaw(t('Are you sure you want to remove %user from the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
  570. $this->drupalPost($confirm_url, NULL, t('Unsubscribe'));
  571. $this->assertRaw(t('%user was unsubscribed from the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber remved from newsletter'));
  572. // Visit the newsletter/subscriptions page with the hash.
  573. $subscriber = simplenews_subscriber_load_by_mail($mail);
  574. $hash = simplenews_generate_hash($subscriber->mail, $subscriber->snid, $tid);
  575. $this->drupalGet('newsletter/subscriptions/' . $hash);
  576. $this->assertText(t('Subscriptions for @mail', array('@mail' => $mail)));
  577. $edit = array(
  578. 'newsletters[' . $tid . ']' => TRUE,
  579. );
  580. $this->drupalPost(NULL, $edit, t('Update'));
  581. // Make sure the user is not yet subscribed.
  582. $subscriber = simplenews_subscriber_load_by_mail($mail);
  583. $this->assertTrue(empty($subscriber->tids));
  584. $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_UNCONFIRMED, $subscriber->newsletter_subscription[$tid]->status);
  585. $mails = $this->drupalGetMails();
  586. $body = $mails[7]['body'];
  587. $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
  588. $found = preg_match($pattern, $body, $match);
  589. $confirm_url = $match[0];
  590. $this->assertTrue($found, t('Confirmation URL found: @url', array('@url' => $confirm_url)));
  591. $this->drupalGet($confirm_url);
  592. $newsletter = taxonomy_term_load($tid);
  593. $this->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => $newsletter->name)), t('Subscription confirmation found.'));
  594. $this->drupalPost($confirm_url, NULL, t('Subscribe'));
  595. $this->assertRaw(t('%user was added to the %newsletter mailing list.', array('%user' => $mail, '%newsletter' => $newsletter->name)), t('Anonymous subscriber added to newsletter'));
  596. // Make sure the subscription is confirmed now.
  597. $subscriber = simplenews_subscriber_load_by_mail($mail);
  598. $this->assertTrue(isset($subscriber->tids[$tid]));
  599. $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED, $subscriber->newsletter_subscription[$tid]->status);
  600. // Attemt to fetch the page using an invalid hash format.
  601. $this->drupalGet('newsletter/subscriptions/' . strrev($hash));
  602. $this->assertResponse(404);
  603. // Attemt to fetch the page using a wrong hash but correct format.
  604. $this->drupalGet('newsletter/subscriptions/' . simplenews_generate_hash($subscriber->mail . 'a', $subscriber->snid, $tid));
  605. $this->assertResponse(404);
  606. // Attempt to unsubscribe a non-existing subscriber.
  607. $mail = $this->randomEmail();
  608. $edit = array(
  609. 'mail' => $mail,
  610. 'newsletters[' . $tid . ']' => TRUE,
  611. );
  612. $this->drupalPost('newsletter/subscriptions', $edit, t('Unsubscribe'));
  613. $this->assertText(t('You will receive a confirmation e-mail shortly containing further instructions on how to cancel your subscription.'));
  614. $mails = $this->drupalGetMails();
  615. $body = $mails[8]['body'];
  616. // Remove line breaks from body in case the string is split.
  617. $body = str_replace("\n", ' ', $body);
  618. debug($body);
  619. $this->assertTrue(strpos($body, 'is not subscribed to this mailing list') !== FALSE);
  620. }
  621. /**
  622. * Test anonymous subscription with single opt in.
  623. *
  624. * Steps performed:
  625. * 0. Preparation
  626. * 1. Subscribe anonymous via block
  627. */
  628. function testSubscribeAnonymousSingle() {
  629. // 0. Preparation
  630. // Login admin
  631. // Create single opt in newsletter.
  632. // Set permission for anonymous to subscribe
  633. // Enable newsletter block
  634. // Logout admin
  635. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer content types', 'administer nodes', 'access administration pages', 'administer permissions', 'administer newsletters'));
  636. $this->drupalLogin($admin_user);
  637. $this->setAnonymousUserSubscription(TRUE);
  638. // Setup subscription block with subscription form.
  639. $block_settings = array(
  640. 'message' => $this->randomName(4),
  641. 'form' => '1',
  642. 'link to previous' => FALSE,
  643. 'previous issues' => FALSE,
  644. 'rss feed' => TRUE,
  645. );
  646. $this->drupalGet('admin/config/services/simplenews');
  647. $this->clickLink(t('Add newsletter category'));
  648. $edit = array(
  649. 'name' => $this->randomName(),
  650. 'description' => $this->randomString(20),
  651. 'opt_inout' => 'single',
  652. );
  653. $this->drupalPost(NULL, $edit, t('Save'));
  654. // @todo: Don't hardcode this.
  655. $tid = 2;
  656. $this->setupSubscriptionBlock($tid, $block_settings);
  657. $this->drupalLogout();
  658. // 1. Subscribe anonymous via block
  659. // Subscribe + submit
  660. // Assert confirmation message
  661. // Verify subscription state.
  662. $mail = $this->randomEmail(8, 'testmail');
  663. $edit = array(
  664. 'mail' => $mail,
  665. );
  666. $this->drupalPost(NULL, $edit, t('Subscribe'));
  667. $this->assertText(t('You have been subscribed.'), t('Anonymous subscriber added to newsletter'));
  668. $subscriber = simplenews_subscriber_load_by_mail($mail);
  669. $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED, $subscriber->newsletter_subscription[$tid]->status);
  670. // Unsubscribe again.
  671. $edit = array(
  672. 'mail' => $mail,
  673. 'newsletters[' . $tid . ']' => TRUE,
  674. );
  675. $this->drupalPost('newsletter/subscriptions', $edit, t('Unsubscribe'));
  676. $subscriber = simplenews_subscriber_load_by_mail($mail);
  677. $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_UNSUBSCRIBED, $subscriber->newsletter_subscription[$tid]->status);
  678. }
  679. /**
  680. * testSubscribeAuthenticated
  681. *
  682. * Steps performed:
  683. * 0. Preparation
  684. * 1. Subscribe authenticated via block
  685. * 2. Unsubscribe authenticated via subscription page
  686. * 3. Subscribe authenticated via subscription page
  687. * 4. Unsubscribe authenticated via account page
  688. * 5. Subscribe authenticated via account page
  689. * 6. Subscribe authenticated via multi block
  690. */
  691. function testSubscribeAuthenticated() {
  692. // 0. Preparation
  693. // Login admin
  694. // Set permission for anonymous to subscribe
  695. // Enable newsletter block
  696. // Logout admin
  697. // Login Subscriber
  698. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer content types', 'administer nodes', 'access administration pages', 'administer permissions'));
  699. $this->drupalLogin($admin_user);
  700. $this->setAnonymousUserSubscription(TRUE);
  701. // Setup subscription block with subscription form.
  702. $block_settings = array(
  703. 'message' => $this->randomName(4),
  704. 'form' => '1',
  705. 'link to previous' => FALSE,
  706. 'previous issues' => FALSE,
  707. 'rss feed' => TRUE,
  708. );
  709. $tid = $this->getRandomNewsletter();
  710. $this->setupSubscriptionBlock($tid, $block_settings);
  711. $this->drupalLogout();
  712. $subscriber_user = $this->drupalCreateUser(array('subscribe to newsletters'));
  713. $this->drupalLogin($subscriber_user);
  714. // 1. Subscribe authenticated via block
  715. // Subscribe + submit
  716. // Assert confirmation message
  717. $this->drupalPost('', NULL, t('Subscribe'));
  718. $this->assertText(t('You have been subscribed.'), t('Authenticated user subscribed using the subscription block.'));
  719. // 2. Unsubscribe authenticated via subscription page
  720. // Unsubscribe + submit
  721. // Assert confirmation message
  722. $edit = array(
  723. "newsletters[$tid]" => 0,
  724. );
  725. $this->drupalPost('newsletter/subscriptions', $edit, t('Update'));
  726. $this->assertRaw(t('The newsletter subscriptions for %mail have been updated.', array('%mail' => $subscriber_user->mail)), t('Authenticated user unsubscribed on the subscriptions page.'));
  727. // 3. Subscribe authenticated via subscription page
  728. // Subscribe + submit
  729. // Assert confirmation message
  730. $edit = array(
  731. "newsletters[$tid]" => '1',
  732. );
  733. $this->drupalPost('newsletter/subscriptions', $edit, t('Update'));
  734. $this->assertRaw(t('The newsletter subscriptions for %mail have been updated.', array('%mail' => $subscriber_user->mail)), t('Authenticated user subscribed on the subscriptions page.'));
  735. // 4. Unsubscribe authenticated via account page
  736. // Unsubscribe + submit
  737. // Assert confirmation message
  738. $edit = array(
  739. "newsletters[$tid]" => FALSE,
  740. );
  741. $url = 'user/' . $subscriber_user->uid . '/edit/simplenews';
  742. $this->drupalPost($url, $edit, t('Save'));
  743. $this->assertRaw(t('The changes have been saved.', array('%mail' => $subscriber_user->mail)), t('Authenticated user unsubscribed on the account page.'));
  744. $subscriber = simplenews_subscriber_load_by_mail($subscriber_user->mail);
  745. $subscription = db_query('SELECT * FROM {simplenews_subscription} WHERE snid = :snid AND tid = :tid', array(':snid' => $subscriber->snid, ':tid' => $tid))->fetchObject();
  746. $this->assertEqual(SIMPLENEWS_SUBSCRIPTION_STATUS_UNSUBSCRIBED, $subscription->status, t('Subscription is unsubscribed'));
  747. // 5. Subscribe authenticated via account page
  748. // Subscribe + submit
  749. // Assert confirmation message
  750. $edit = array(
  751. "newsletters[$tid]" => '1',
  752. );
  753. $url = 'user/' . $subscriber_user->uid . '/edit/simplenews';
  754. $this->drupalPost($url, $edit, t('Save'));
  755. $this->assertRaw(t('The changes have been saved.', array('%mail' => $subscriber_user->mail)), t('Authenticated user unsubscribed on the account page.'));
  756. // Subscribe authenticated via multi block
  757. $this->drupalLogin($admin_user);
  758. // Enable the multi-sign up block.
  759. $this->setupSubscriptionBlock(0);
  760. // Disable the category block.
  761. $edit = array(
  762. 'blocks[simplenews_' . $tid . '][region]' => -1,
  763. );
  764. $this->drupalPost(NULL, $edit, t('Save blocks'));
  765. $this->drupalLogout();
  766. // Try to submit multi-signup form without selecting a category.
  767. $subscriber_user2 = $this->drupalCreateUser(array('subscribe to newsletters'));
  768. $this->drupalLogin($subscriber_user2);
  769. // Check that the user has only access to his own subscriptions page.
  770. $this->drupalGet('user/' . $subscriber_user->uid . '/edit/simplenews');
  771. $this->assertResponse(403);
  772. $this->drupalGet('user/' . $subscriber_user2->uid . '/edit/simplenews');
  773. $this->assertResponse(200);
  774. $this->assertNoField('mail');
  775. $this->drupalPost(NULL, array(), t('Update'));
  776. $this->assertText(t('The newsletter subscriptions for @mail have been updated.', array('@mail' => $subscriber_user2->mail)));
  777. // Nothing should have happened.
  778. $this->assertNoFieldChecked('edit-newsletters-' . $tid);
  779. // Now fill out the form and try again.
  780. $edit = array(
  781. 'newsletters[' . $tid . ']' => TRUE,
  782. );
  783. $this->drupalPost(NULL, $edit, t('Update'));
  784. $this->assertText(t('The newsletter subscriptions for @mail have been updated.', array('@mail' => $subscriber_user2->mail)));
  785. $this->assertFieldChecked('edit-newsletters-' . $tid);
  786. // Unsubscribe.
  787. $edit = array(
  788. 'newsletters[' . $tid . ']' => FALSE,
  789. );
  790. $this->drupalPost(NULL, $edit, t('Update'));
  791. $this->assertText(t('The newsletter subscriptions for @mail have been updated.', array('@mail' => $subscriber_user2->mail)));
  792. $this->assertNoFieldChecked('edit-newsletters-' . $tid);
  793. // And now the same for the newsletter/subscriptions page.
  794. $subscriber_user3 = $this->drupalCreateUser(array('subscribe to newsletters'));
  795. $this->drupalLogin($subscriber_user3);
  796. $this->assertNoField('mail');
  797. $this->drupalPost('newsletter/subscriptions', array(), t('Update'));
  798. $this->assertText(t('The newsletter subscriptions for @mail have been updated.', array('@mail' => $subscriber_user3->mail)));
  799. // Nothing should have happened.
  800. $this->assertNoFieldChecked('edit-newsletters-' . $tid);
  801. // Now fill out the form and try again.
  802. $edit = array(
  803. 'newsletters[' . $tid . ']' => TRUE,
  804. );
  805. $this->drupalPost('newsletter/subscriptions', $edit, t('Update'));
  806. $this->assertText(t('The newsletter subscriptions for @mail have been updated.', array('@mail' => $subscriber_user3->mail)));
  807. $this->assertFieldChecked('edit-newsletters-' . $tid);
  808. // Unsubscribe.
  809. $edit = array(
  810. 'newsletters[' . $tid . ']' => FALSE,
  811. );
  812. $this->drupalPost('newsletter/subscriptions', $edit, t('Update'));
  813. $this->assertText(t('The newsletter subscriptions for @mail have been updated.', array('@mail' => $subscriber_user3->mail)));
  814. $this->assertNoFieldChecked('edit-newsletters-' . $tid);
  815. }
  816. }
  817. /**
  818. * @todo:
  819. * Newsletter node create, send draft, send final
  820. */
  821. class SimpleNewsAdministrationTestCase extends SimplenewsTestCase {
  822. /**
  823. * Implement getInfo().
  824. */
  825. function getInfo() {
  826. return array(
  827. 'name' => t('Simplenews administration'),
  828. 'description' => t('Managing of newsletter categories and content types.'),
  829. 'group' => t('Simplenews'),
  830. );
  831. }
  832. /**
  833. * Overrides SimplenewsTestCase::setUp().
  834. */
  835. public function setUp() {
  836. parent::setUp(array('block'));
  837. }
  838. /**
  839. * Test various combinations of newsletter category settings.
  840. */
  841. function testCategorySettings() {
  842. // Allow registration of new accounts without approval.
  843. variable_set('user_register', 1);
  844. variable_set('user_email_verification', FALSE);
  845. // Allow authenticated users to subscribe.
  846. $this->setAuthenticatedUserSubscription(TRUE);
  847. $admin_user = $this->drupalCreateUser(array(
  848. 'administer blocks',
  849. 'administer content types',
  850. 'administer nodes',
  851. 'access administration pages',
  852. 'administer permissions',
  853. 'administer newsletters',
  854. 'administer simplenews subscriptions',
  855. 'create simplenews content',
  856. 'send newsletter',
  857. ));
  858. $this->drupalLogin($admin_user);
  859. $this->drupalGet('admin/config/services/simplenews');
  860. // Create a category for all possible setting combinations.
  861. $new_account = array('none', 'off', 'on', 'silent');
  862. $opt_inout = array('hidden', 'single', 'double');
  863. $block = array('block' => TRUE, 'noblock' => FALSE);
  864. foreach ($new_account as $new_account_setting) {
  865. foreach ($opt_inout as $opt_inout_setting) {
  866. foreach ($block as $name => $value) {
  867. $this->clickLink(t('Add newsletter category'));
  868. $edit = array(
  869. 'name' => implode('-', array($new_account_setting, $opt_inout_setting, $name)),
  870. 'description' => $this->randomString(20),
  871. 'new_account' => $new_account_setting,
  872. 'opt_inout' => $opt_inout_setting,
  873. 'block' => $value,
  874. 'priority' => rand(0, 5),
  875. 'receipt' => rand(0, 1) ? TRUE : FALSE,
  876. 'from_name' => $this->randomName(),
  877. 'from_address' => $this->randomEmail(),
  878. );
  879. $this->drupalPost(NULL, $edit, t('Save'));
  880. }
  881. }
  882. }
  883. drupal_static_reset('simplenews_categories_load_multiple');
  884. $categories = simplenews_categories_load_multiple();
  885. // Check block settings.
  886. $this->drupalGet('admin/structure/block');
  887. //blocks[simplenews_42][region]
  888. foreach ($categories as $category) {
  889. if (strpos($category->name, '-') === FALSE) {
  890. continue;
  891. }
  892. list($new_account_setting, $opt_inout_setting, $block) = explode('-', $category->name);
  893. if ($block == 'block' && $opt_inout_setting != 'hidden') {
  894. $this->assertField('blocks[simplenews_' . $category->tid . '][region]', t('Block is displayed for category'));
  895. }
  896. else {
  897. $this->assertNoField('blocks[simplenews_' . $category->tid . '][region]', t('Block is not displayed for category'));
  898. }
  899. }
  900. // Check registration form.
  901. $this->drupalLogout();
  902. $this->drupalGet('user/register');
  903. foreach ($categories as $category) {
  904. if (strpos($category->name, '-') === FALSE) {
  905. continue;
  906. }
  907. // Explicitly subscribe to the off-double-block newsletter.
  908. if ($category->name == 'off-double-block') {
  909. $off_double_block_tid = $category->tid;
  910. }
  911. list($new_account_setting, $opt_inout_setting, $block) = explode('-', $category->name);
  912. if ($category->new_account == 'on' && $category->opt_inout != 'hidden') {
  913. $this->assertFieldChecked('edit-newsletters-' . $category->tid);
  914. }
  915. elseif ($category->new_account == 'off' && $category->opt_inout != 'hidden') {
  916. $this->assertNoFieldChecked('edit-newsletters-' . $category->tid);
  917. }
  918. else {
  919. $this->assertNoField('newsletters[' . $category->tid . ']', t('Hidden or silent newsletter category is not shown.'));
  920. }
  921. }
  922. // Register a new user through the form.
  923. $edit = array(
  924. 'name' => $this->randomName(),
  925. 'mail' => $this->randomEmail(),
  926. 'pass[pass1]' => $pass = $this->randomName(),
  927. 'pass[pass2]' => $pass,
  928. 'newsletters[' . $off_double_block_tid . ']' => $off_double_block_tid,
  929. );
  930. $this->drupalPost(NULL, $edit, t('Create new account'));
  931. // Verify confirmation messages.
  932. $this->assertText(t('Registration successful. You are now logged in.'));
  933. foreach ($categories as $category) {
  934. // Check confirmation message for all on and non-hidden newsletters and
  935. // the one that was explicitly selected.
  936. if (($category->new_account == 'on' && $category->opt_inout != 'hidden') || $category->name == 'off-double-block') {
  937. $this->assertText(t('You have been subscribed to @name.', array('@name' => $category->name)));
  938. }
  939. else {
  940. // All other newsletters must not show a message, e.g. those which were
  941. // subscribed silently.
  942. $this->assertNoText(t('You have been subscribed to @name.', array('@name' => $category->name)));
  943. }
  944. }
  945. // Log out again.
  946. $this->drupalLogout();
  947. // Get the user id and do a login through the drupalLogin() function.
  948. $uid = db_query('SELECT uid FROM {users} WHERE name = :name', array(':name' => $edit['name']))->fetchField();
  949. $user = user_load($uid);
  950. // Set the password so that the login works.
  951. $user->pass_raw = $edit['pass[pass1]'];
  952. // Verify newsletter subscription pages.
  953. $this->drupalLogin($user);
  954. foreach (array('newsletter/subscriptions', 'user/' . $user->uid . '/edit/simplenews') as $path) {
  955. $this->drupalGet($path);
  956. foreach ($categories as $category) {
  957. if (strpos($category->name, '-') === FALSE) {
  958. continue;
  959. }
  960. list($new_account_setting, $opt_inout_setting, $block) = explode('-', $category->name);
  961. if ($category->opt_inout == 'hidden') {
  962. $this->assertNoField('newsletters[' . $category->tid . ']', t('Hidden newsletter category is not shown.'));
  963. }
  964. elseif ($category->new_account == 'on' || $category->name == 'off-double-block' || $category->new_account == 'silent') {
  965. // All on, silent and the explicitly selected category should be checked.
  966. $this->assertFieldChecked('edit-newsletters-' . $category->tid);
  967. }
  968. else {
  969. $this->assertNoFieldChecked('edit-newsletters-' . $category->tid);
  970. }
  971. }
  972. }
  973. // Unsubscribe from a newsletter category.
  974. $edit = array(
  975. 'newsletters[' . $off_double_block_tid . ']' => FALSE,
  976. );
  977. $this->drupalPost(NULL, $edit, t('Save'));
  978. $this->assertNoFieldChecked('edit-newsletters-' . $off_double_block_tid);
  979. // Get a category which has the block enabled.
  980. foreach ($categories as $category) {
  981. // The default category is missing the from mail address. Use another one.
  982. if ($category->block == TRUE && $category->tid != 1 && $category->opt_inout != 'hidden') {
  983. $edit_category = $category;
  984. break;
  985. }
  986. }
  987. $this->drupalLogin($admin_user);
  988. $this->setupSubscriptionBlock($edit_category->tid, $settings = array(
  989. 'issue count' => 2,
  990. 'previous issues' => 1,
  991. ));
  992. // Create a bunch of newsletters.
  993. $generated_names = array();
  994. $date = strtotime('monday this week');
  995. for ($index = 0; $index < 3; $index++) {
  996. $name = $this->randomName();
  997. $generated_names[] = $name;
  998. $this->drupalGet('node/add/simplenews');
  999. $edit = array(
  1000. 'title' => $name,
  1001. 'field_simplenews_term[und]' => $edit_category->tid,
  1002. 'date' => date('c', strtotime('+' . $index . ' day', $date)),
  1003. );
  1004. $this->drupalPost(NULL, $edit, ('Save'));
  1005. $this->clickLink(t('Newsletter'));
  1006. $this->drupalPost(NULL, array('simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW), t('Submit'));
  1007. }
  1008. // Display the two recent issues.
  1009. $this->drupalGet('');
  1010. $this->assertText(t('Previous issues'), 'Should display recent issues.');
  1011. $displayed_issues = $this->xpath("//div[@class='issues-list']/div/ul/li/a");
  1012. $this->assertEqual(count($displayed_issues), 2, 'Displys two recent issues.');
  1013. $this->assertFalse(in_array($generated_names[0], $displayed_issues));
  1014. $this->assertTrue(in_array($generated_names[1], $displayed_issues));
  1015. $this->assertTrue(in_array($generated_names[2], $displayed_issues));
  1016. $this->drupalGet('admin/config/services/simplenews/categories/' . $edit_category->tid . '/edit');
  1017. $this->assertFieldByName('name', $edit_category->name, t('Category name is displayed when editing'));
  1018. $this->assertFieldByName('description', $edit_category->description, t('Category description is displayed when editing'));
  1019. $edit = array('block' => FALSE);
  1020. $this->drupalPost(NULL, $edit, t('Save'));
  1021. $updated_category = simplenews_category_load($edit_category->tid);
  1022. $this->assertEqual(0, $updated_category->block, t('Block for category disabled'));
  1023. $this->drupalGet('admin/structure/block');
  1024. $this->assertNoText($edit_category->name, t('Category block was removed'));
  1025. // Delete a category.
  1026. $this->drupalGet('admin/config/services/simplenews/categories/' . $edit_category->tid . '/edit');
  1027. $edit = array();
  1028. $this->drupalPost(NULL, $edit, t('Delete'));
  1029. $this->drupalPost(NULL, $edit, t('Delete'));
  1030. // Verify that the category has been deleted.
  1031. $this->assertFalse(simplenews_category_load($edit_category->tid));
  1032. $this->assertFalse(db_query('SELECT tid FROM {simplenews_category} WHERE tid = :tid', array(':tid' => $edit_category->tid))->fetchField());
  1033. }
  1034. /**
  1035. * Test newsletter subscription management.
  1036. *
  1037. * Steps performed:
  1038. *
  1039. */
  1040. function testSubscriptionManagement() {
  1041. $admin_user = $this->drupalCreateUser(array('administer newsletters', 'administer simplenews settings', 'administer simplenews subscriptions', 'administer taxonomy'));
  1042. $this->drupalLogin($admin_user);
  1043. // Create a second category.
  1044. $edit = array(
  1045. 'name' => $name = $this->randomName(),
  1046. );
  1047. $this->drupalPost('admin/config/services/simplenews/add', $edit, t('Save'));
  1048. // Add a number of users to each category separately and then add another
  1049. // bunch to both.
  1050. $subscribers = array();
  1051. drupal_static_reset('simplenews_categories_load_multiple');
  1052. $categories = simplenews_categories_load_multiple();
  1053. $groups = array();
  1054. foreach (array_keys($categories) as $tid) {
  1055. $groups[$tid] = array($tid);
  1056. }
  1057. $groups['all'] = array_keys($groups);
  1058. $subscribers_flat = array();
  1059. foreach ($groups as $key => $group) {
  1060. for ($i = 0; $i < 5; $i++) {
  1061. $mail = $this->randomEmail();
  1062. $subscribers[$key][$mail] = $mail;
  1063. $subscribers_flat[$mail] = $mail;
  1064. }
  1065. }
  1066. // Create a user and assign him one of the mail addresses of the all group.
  1067. $user = $this->drupalCreateUser(array('subscribe to newsletters'));
  1068. // Make sure that user_save() does not update the user object, as it will
  1069. // override the pass_raw property which we'll need to log this user in
  1070. // later on.
  1071. $user_mail = current($subscribers['all']);
  1072. user_save(clone $user, array('mail' => $user_mail));
  1073. $delimiters = array(',', ' ', "\n");
  1074. $this->drupalGet('admin/people/simplenews');
  1075. $i = 0;
  1076. foreach ($groups as $key => $group) {
  1077. $this->clickLink(t('Mass subscribe'));
  1078. $edit = array(
  1079. // Implode with a different, supported delimiter for each group.
  1080. 'emails' => implode($delimiters[$i++], $subscribers[$key]),
  1081. );
  1082. foreach ($group as $tid) {
  1083. $edit['newsletters[' . $tid . ']'] = TRUE;
  1084. }
  1085. $this->drupalPost(NULL, $edit, t('Subscribe'));
  1086. }
  1087. // The user to which the mail was assigned should be listed too.
  1088. $this->assertText($user->name);
  1089. // Verify that all addresses are displayed in the table.
  1090. $mail_addresses = $this->xpath('//tr/td[2]');
  1091. $this->assertEqual(15, count($mail_addresses));
  1092. foreach ($mail_addresses as $mail_address) {
  1093. $mail_address = (string) $mail_address;
  1094. $this->assertTrue(isset($subscribers_flat[$mail_address]));
  1095. unset($subscribers_flat[$mail_address]);
  1096. }
  1097. // All entries of the array should be removed by now.
  1098. $this->assertTrue(empty($subscribers_flat));
  1099. // Limit list to subscribers of the first category only.
  1100. reset($groups);
  1101. $first = key($groups);
  1102. // Build a flat list of the subscribers of this list.
  1103. $subscribers_flat = array_merge($subscribers[$first], $subscribers['all']);
  1104. $edit = array(
  1105. 'list' => 'tid-' . $first,
  1106. );
  1107. $this->drupalPost(NULL, $edit, t('Filter'));
  1108. // Verify that all addresses are displayed in the table.
  1109. $mail_addresses = $this->xpath('//tr/td[2]');
  1110. $this->assertEqual(10, count($mail_addresses));
  1111. foreach ($mail_addresses as $mail_address) {
  1112. $mail_address = (string) $mail_address;
  1113. $this->assertTrue(isset($subscribers_flat[$mail_address]));
  1114. unset($subscribers_flat[$mail_address]);
  1115. }
  1116. // All entries of the array should be removed by now.
  1117. $this->assertTrue(empty($subscribers_flat));
  1118. // Filter a single mail address, the one assigned to a user.
  1119. $edit = array(
  1120. 'email' => drupal_substr(current($subscribers['all']), 0, 4)
  1121. );
  1122. $this->drupalPost(NULL, $edit, t('Filter'));
  1123. $rows = $this->xpath('//tbody/tr');
  1124. $this->assertEqual(1, count($rows));
  1125. $this->assertEqual(current($subscribers['all']), (string) $rows[0]->td[1]);
  1126. $this->assertEqual($user->name, (string) $rows[0]->td[2]->a);
  1127. // Reset the filter.
  1128. $this->drupalPost(NULL, array(), t('Reset'));
  1129. // Test mass-unsubscribe, unsubscribe one from the first group and one from
  1130. // the all group, but only from the first newsletter category.
  1131. $first_mail = array_rand($subscribers[$first]);
  1132. $all_mail = array_rand($subscribers['all']);
  1133. unset($subscribers[$first][$first_mail]);
  1134. $edit = array(
  1135. 'emails' => $first_mail . ', ' . $all_mail,
  1136. 'newsletters[' . $first . ']' => TRUE,
  1137. );
  1138. $this->clickLink(t('Mass unsubscribe'));
  1139. $this->drupalPost(NULL, $edit, t('Unsubscribe'));
  1140. // The all mail is still displayed because it's still subscribed to the
  1141. // second category. Reload the page to get rid of the confirmation
  1142. // message.
  1143. $this->drupalGet('admin/people/simplenews');
  1144. $this->assertNoText($first_mail);
  1145. $this->assertText($all_mail);
  1146. // Limit to first category, the all mail shouldn't be shown anymore.
  1147. $edit = array(
  1148. 'list' => 'tid-' . $first,
  1149. );
  1150. $this->drupalPost(NULL, $edit, t('Filter'));
  1151. $this->assertNoText($first_mail);
  1152. $this->assertNoText($all_mail);
  1153. // Check exporting.
  1154. $this->clickLink(t('Export'));
  1155. $this->drupalPost(NULL, array('newsletters[' . $first . ']' => TRUE), t('Export'));
  1156. $export_field = $this->xpath($this->constructFieldXpath('name', 'emails'));
  1157. $exported_mails = (string) $export_field[0];
  1158. foreach ($subscribers[$first] as $mail) {
  1159. $this->assertTrue(strpos($exported_mails, $mail) !== FALSE, t('Mail address exported correctly.'));
  1160. }
  1161. foreach ($subscribers['all'] as $mail) {
  1162. if ($mail != $all_mail) {
  1163. $this->assertTrue(strpos($exported_mails, $mail) !== FALSE, t('Mail address exported correctly.'));
  1164. }
  1165. else {
  1166. $this->assertFALSE(strpos($exported_mails, $mail) !== FALSE, t('Unsubscribed mail address not exported.'));
  1167. }
  1168. }
  1169. // Only export unsubscribed mail addresses.
  1170. $edit = array(
  1171. 'subscribed[subscribed]' => FALSE,
  1172. 'subscribed[unsubscribed]' => TRUE,
  1173. 'newsletters[' . $first . ']' => TRUE,
  1174. );
  1175. $this->drupalPost(NULL, $edit, t('Export'));
  1176. $export_field = $this->xpath($this->constructFieldXpath('name', 'emails'));
  1177. $exported_mails = (string) $export_field[0];
  1178. $exported_mails = explode(', ', $exported_mails);
  1179. $this->assertEqual(2, count($exported_mails));
  1180. $this->assertTrue(in_array($all_mail, $exported_mails));
  1181. $this->assertTrue(in_array($first_mail, $exported_mails));
  1182. // Make sure there are unconfirmed subscriptions.
  1183. $unconfirmed = array();
  1184. $unconfirmed[] = $this->randomEmail();
  1185. $unconfirmed[] = $this->randomEmail();
  1186. foreach ($unconfirmed as $mail) {
  1187. simplenews_subscribe_user($mail, $first, TRUE);
  1188. }
  1189. // Only export unconfirmed mail addresses.
  1190. $edit = array(
  1191. 'subscribed[subscribed]' => FALSE,
  1192. 'subscribed[unconfirmed]' => TRUE,
  1193. 'subscribed[unsubscribed]' => FALSE,
  1194. 'newsletters[' . $first . ']' => TRUE,
  1195. );
  1196. $this->drupalPost(NULL, $edit, t('Export'));
  1197. $export_field = $this->xpath($this->constructFieldXpath('name', 'emails'));
  1198. $exported_mails = (string) $export_field[0];
  1199. $exported_mails = explode(', ', $exported_mails);
  1200. $this->assertEqual(2, count($exported_mails));
  1201. $this->assertTrue(in_array($unconfirmed[0], $exported_mails));
  1202. $this->assertTrue(in_array($unconfirmed[1], $exported_mails));
  1203. // Make sure the user is subscribed to the first tid.
  1204. simplenews_subscribe_user($user_mail, $first, FALSE);
  1205. module_load_include('inc', 'simplenews', 'includes/simplenews.admin');
  1206. $before_count = simplenews_count_subscriptions($first);
  1207. // Block the user.
  1208. user_save(clone $user, array('status' => 0));
  1209. $this->drupalGet('admin/people/simplenews');
  1210. // Verify updated subscriptions count.
  1211. drupal_static_reset('simplenews_count_subscriptions');
  1212. $after_count = simplenews_count_subscriptions($first);
  1213. $this->assertEqual($before_count - 1, $after_count, t('Blocked users are not counted in subscription count.'));
  1214. // Test mass subscribe with previously unsubscribed users.
  1215. for ($i = 0; $i < 3; $i++) {
  1216. $tested_subscribers[] = $this->randomEmail();
  1217. }
  1218. simplenews_subscribe_user($tested_subscribers[0], $first, FALSE);
  1219. simplenews_subscribe_user($tested_subscribers[1], $first, FALSE);
  1220. simplenews_unsubscribe_user($tested_subscribers[0], $first, FALSE);
  1221. simplenews_unsubscribe_user($tested_subscribers[1], $first, FALSE);
  1222. $unsubscribed = implode(', ', array_slice($tested_subscribers, 0, 2));
  1223. $edit = array(
  1224. 'emails' => implode(', ', $tested_subscribers),
  1225. 'newsletters[' . $first . ']' => TRUE,
  1226. );
  1227. $this->drupalPost('admin/people/simplenews/import', $edit, t('Subscribe'));
  1228. drupal_static_reset('simplenews_subscriber_load_multiple');
  1229. drupal_static_reset('simplenews_user_is_subscribed');
  1230. $this->assertFalse(simplenews_user_is_subscribed($tested_subscribers[0], $first, t('Subscriber not resubscribed through mass subscription.')));
  1231. $this->assertFalse(simplenews_user_is_subscribed($tested_subscribers[1], $first, t('Subscriber not resubscribed through mass subscription.')));
  1232. $this->assertTrue(simplenews_user_is_subscribed($tested_subscribers[2], $first, t('Subscriber subscribed through mass subscription.')));
  1233. $substitutes = array('@name' => check_plain(_simplenews_newsletter_name(simplenews_category_load($first))), '@mail' => $unsubscribed);
  1234. $this->assertText(t('The following addresses were skipped because they have previously unsubscribed from @name: @mail.', $substitutes));
  1235. $this->assertText(t("If you would like to resubscribe them, use the 'Force resubscription' option."));
  1236. // Test mass subscribe with previously unsubscribed users and force
  1237. // resubscription.
  1238. $tested_subscribers[2] = $this->randomEmail();
  1239. $edit = array(
  1240. 'emails' => implode(', ', $tested_subscribers),
  1241. 'newsletters[' . $first . ']' => TRUE,
  1242. 'resubscribe' => TRUE,
  1243. );
  1244. $this->drupalPost('admin/people/simplenews/import', $edit, t('Subscribe'));
  1245. drupal_static_reset('simplenews_subscriber_load_multiple');
  1246. drupal_static_reset('simplenews_user_is_subscribed');
  1247. $this->assertTrue(simplenews_user_is_subscribed($tested_subscribers[0], $first, t('Subscriber resubscribed trough mass subscription.')));
  1248. $this->assertTrue(simplenews_user_is_subscribed($tested_subscribers[1], $first, t('Subscriber resubscribed trough mass subscription.')));
  1249. $this->assertTrue(simplenews_user_is_subscribed($tested_subscribers[2], $first, t('Subscriber subscribed trough mass subscription.')));
  1250. // Delete newsletter category.
  1251. $this->drupalPost('taxonomy/term/' . $first . '/edit', array(), t('Delete'));
  1252. $this->assertText(t('This taxonomy term is part of simplenews newsletter category @name. Deleting this term will delete the newsletter category and all subscriptions to category @name. This action cannot be undone.', array('@name' => $categories[$first]->name)), t('Confirmation message displayed.'));
  1253. $this->drupalPost(NULL, array(), t('Delete'));
  1254. $this->assertText(t('All subscriptions to newsletter @newsletter have been deleted.', array('@newsletter' => $categories[$first]->name)));
  1255. // Verify that all related data has been deleted.
  1256. $this->assertFalse(simplenews_category_load($first));
  1257. $this->assertFalse(db_query('SELECT tid FROM {simplenews_category} WHERE tid = :tid', array(':tid' => $first))->fetchField());
  1258. $this->assertFalse(db_query('SELECT * FROM {block} WHERE module = :module AND delta = :tid', array(':module' => 'simplenews', ':tid' => $first))->fetchField());
  1259. // Verify that all subscriptions of that category have been removed.
  1260. $this->drupalGet('admin/people/simplenews');
  1261. foreach ($subscribers[$first] as $mail) {
  1262. $this->assertNoText($mail);
  1263. }
  1264. // Reset list and click on the first subscriber.
  1265. $this->drupalPost(NULL, array(), t('Reset'));
  1266. $this->clickLink(t('edit'));
  1267. // Get the subscriber id from the path.
  1268. $this->assertTrue(preg_match('|admin/people/simplenews/users/edit/(\d+)$|', $this->getUrl(), $matches), 'Subscriber found');
  1269. $subscriber = simplenews_subscriber_load($matches[1]);
  1270. $this->assertText(t('Subscriptions for @mail', array('@mail' => $subscriber->mail)));
  1271. $this->assertFieldChecked('edit-activated--2');
  1272. // Disable account.
  1273. $edit = array(
  1274. 'activated' => FALSE,
  1275. );
  1276. $this->drupalPost(NULL, $edit, t('Update'));
  1277. drupal_static_reset('simplenews_subscriber_load_multiple');
  1278. drupal_static_reset('simplenews_user_is_subscribed');
  1279. $this->assertFalse(simplenews_user_is_subscribed($subscriber->mail, $this->getRandomNewsletter(), t('Subscriber is not active')));
  1280. // Re-enable account.
  1281. $this->drupalGet('admin/people/simplenews/users/edit/' . $subscriber->snid);
  1282. $this->assertText(t('Subscriptions for @mail', array('@mail' => $subscriber->mail)));
  1283. $this->assertNoFieldChecked('edit-activated--2');
  1284. $edit = array(
  1285. 'activated' => TRUE,
  1286. );
  1287. $this->drupalPost(NULL, $edit, t('Update'));
  1288. drupal_static_reset('simplenews_subscriber_load_multiple');
  1289. drupal_static_reset('simplenews_user_is_subscribed');
  1290. $this->assertTrue(simplenews_user_is_subscribed($subscriber->mail, $this->getRandomNewsletter(), t('Subscriber is active again.')));
  1291. // Remove the category.
  1292. $this->drupalGet('admin/people/simplenews/users/edit/' . $subscriber->snid);
  1293. $this->assertText(t('Subscriptions for @mail', array('@mail' => $subscriber->mail)));
  1294. $edit = array(
  1295. 'newsletters[' . reset($subscriber->tids) . ']' => FALSE,
  1296. );
  1297. $this->drupalPost(NULL, $edit, t('Update'));
  1298. drupal_static_reset('simplenews_subscriber_load_multiple');
  1299. drupal_static_reset('simplenews_user_is_subscribed');
  1300. $this->assertFalse(simplenews_user_is_subscribed($subscriber->mail, reset($subscriber->tids), t('Subscriber not subscribed anymore.')));
  1301. // @todo Test Admin subscriber edit preferred language $subscription->language
  1302. }
  1303. /**
  1304. * Test content type configuration.
  1305. */
  1306. function testContentTypes() {
  1307. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer content types', 'administer nodes', 'access administration pages', 'administer permissions', 'administer newsletters', 'administer simplenews subscriptions', 'bypass node access', 'send newsletter'));
  1308. $this->drupalLogin($admin_user);
  1309. $this->drupalGet('admin/structure/types');
  1310. $this->clickLink(t('Add content type'));
  1311. $edit = array(
  1312. 'name' => $name = $this->randomName(),
  1313. 'type' => $type = drupal_strtolower($name),
  1314. 'simplenews_content_type' => TRUE,
  1315. );
  1316. $this->drupalPost(NULL, $edit, t('Save content type'));
  1317. // Verify that the newsletter settings are shown.
  1318. $this->drupalGet('node/add/' . $type);
  1319. $this->assertText(t('Newsletter category'));
  1320. // Create an issue.
  1321. $edit = array(
  1322. 'title' => $this->randomName(),
  1323. );
  1324. $this->drupalPost(NULL, $edit, ('Save'));
  1325. // Send newsletter.
  1326. $this->clickLink(t('Newsletter'));
  1327. $this->assertText(t('Send newsletter'));
  1328. $this->drupalPost(NULL, array(), t('Submit'));
  1329. $mails = $this->drupalGetMails();
  1330. $this->assertEqual('simplenews_test', $mails[0]['id']);
  1331. // @todo: Test with a custom test mail address.
  1332. $this->assertEqual('user@example.com', $mails[0]['to']);
  1333. $this->assertEqual(t('[Drupal newsletter] @title', array('@title' => $edit['title'])), $mails[0]['subject']);
  1334. // Update the content type, remove the simpletest checkbox.
  1335. $edit = array(
  1336. 'simplenews_content_type' => FALSE,
  1337. );
  1338. $this->drupalPost('admin/structure/types/manage/' . $type, $edit, t('Save content type'));
  1339. // Verify that the newsletter settings are still shown.
  1340. // Note: Previously the field got autoremoved. We leave it remaining due to potential data loss.
  1341. $this->drupalGet('node/add/' . $type);
  1342. $this->assertNoText(t('Replacement patterns'));
  1343. $this->assertText(t('Newsletter category'));
  1344. // @todo: Test node update/delete.
  1345. // Delete content type.
  1346. // @todo: Add assertions.
  1347. $this->drupalPost('admin/structure/types/manage/' . $type . '/delete', array(), t('Delete'));
  1348. }
  1349. }
  1350. /**
  1351. * Tests for I18N integration.
  1352. */
  1353. class SimpleNewsI18nTestCase extends SimplenewsTestCase {
  1354. /**
  1355. * Implementation of getInfo().
  1356. */
  1357. function getInfo() {
  1358. return array(
  1359. 'name' => t('Simplenews I18n'),
  1360. 'description' => t('Translation of newsletter categories'),
  1361. 'group' => t('Simplenews'),
  1362. 'dependencies' => array('i18n_taxonomy', 'variable'),
  1363. );
  1364. }
  1365. function setUp() {
  1366. parent::setUp(array('locale', 'i18n', 'variable', 'i18n_string', 'i18n_taxonomy', 'translation', 'i18n_translation'));
  1367. $this->admin_user = $this->drupalCreateUser(array('bypass node access', 'administer nodes', 'administer languages', 'administer content types', 'access administration pages', 'administer filters', 'administer taxonomy', 'translate interface', 'subscribe to newsletters', 'administer site configuration', 'translate content', 'administer simplenews subscriptions', 'send newsletter'));
  1368. $this->drupalLogin($this->admin_user);
  1369. $this->setUpLanguages();
  1370. }
  1371. /**
  1372. * Install a the specified language if it has not been already. Otherwise make sure that
  1373. * the language is enabled.
  1374. *
  1375. * Copied from Drupali18nTestCase::addLanguage().
  1376. *
  1377. * @param $language_code
  1378. * The language code the check.
  1379. */
  1380. function addLanguage($language_code) {
  1381. // Check to make sure that language has not already been installed.
  1382. $this->drupalGet('admin/config/regional/language');
  1383. if (strpos($this->drupalGetContent(), 'enabled[' . $language_code . ']') === FALSE) {
  1384. // Doesn't have language installed so add it.
  1385. $edit = array();
  1386. $edit['langcode'] = $language_code;
  1387. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  1388. // Make sure we are not using a stale list.
  1389. drupal_static_reset('language_list');
  1390. $languages = language_list('language');
  1391. $this->assertTrue(array_key_exists($language_code, $languages), t('Language was installed successfully.'));
  1392. if (array_key_exists($language_code, $languages)) {
  1393. $this->assertRaw(t('The language %language has been created and can now be used. More information is available on the <a href="@locale-help">help screen</a>.', array('%language' => $languages[$language_code]->name, '@locale-help' => url('admin/help/locale'))), t('Language has been created.'));
  1394. }
  1395. }
  1396. elseif ($this->xpath('//input[@type="checkbox" and @name=:name and @checked="checked"]', array(':name' => 'enabled[' . $language_code . ']'))) {
  1397. // It's installed and enabled. No need to do anything.
  1398. $this->assertTrue(true, 'Language [' . $language_code . '] already installed and enabled.');
  1399. }
  1400. else {
  1401. // It's installed but not enabled. Enable it.
  1402. $this->assertTrue(true, 'Language [' . $language_code . '] already installed.');
  1403. $this->drupalPost(NULL, array('enabled[' . $language_code . ']' => TRUE), t('Save configuration'));
  1404. $this->assertRaw(t('Configuration saved.'), t('Language successfully enabled.'));
  1405. }
  1406. }
  1407. function testCategoryTranslation() {
  1408. $this->drupalLogin($this->admin_user);
  1409. // Make Input Format "Filtered Text" translatable
  1410. $edit = array(
  1411. // The testing profile has no filtered_html mode.
  1412. //'i18n_string_allowed_formats[filtered_html]' => 'filtered_html',
  1413. 'i18n_string_allowed_formats[plain_text]' => 'plain_text',
  1414. );
  1415. $this->drupalPost('admin/config/regional/i18n/strings', $edit, t('Save configuration'));
  1416. $vocabulary = taxonomy_vocabulary_machine_name_load('newsletter');
  1417. $vocabulary->i18n_mode = I18N_MODE_LOCALIZE;
  1418. taxonomy_vocabulary_save($vocabulary);
  1419. drupal_static_reset('i18n_taxonomy_vocabulary_mode');
  1420. // Refresh strings.
  1421. // @todo: simplenews_category_save() should probably take care of this.
  1422. // Currently done separately in simplenews_admin_category_form_submit()
  1423. // for the admin UI.
  1424. $tid = $this->getRandomNewsletter();
  1425. $term = taxonomy_term_load($tid);
  1426. taxonomy_term_save($term);
  1427. $tid = array_shift(simplenews_categories_load_multiple())->tid;
  1428. // Translate term to spanish.
  1429. list($textgroup, $context) = i18n_string_context(array('taxonomy', 'term', $tid, 'name'));
  1430. i18n_string_textgroup($textgroup)->update_translation($context, 'es', $es_name = $this->randomName());
  1431. list($textgroup, $context) = i18n_string_context(array('taxonomy', 'term', $tid, 'description'));
  1432. i18n_string_textgroup($textgroup)->update_translation($context, 'es', $es_description = $this->randomName());
  1433. // Visit newsletter selection page in english.
  1434. $this->drupalGet('user/' . $this->admin_user->uid . '/edit/simplenews');
  1435. $this->assertText(t('Drupal newsletter'));
  1436. // And now in spanish.
  1437. $this->drupalGet('es/user/' . $this->admin_user->uid . '/edit/simplenews');
  1438. $this->assertText($es_name, t('Category name is translated.'));
  1439. }
  1440. function testContentTranslation() {
  1441. // Sign up two users, one in english, another in spanish.
  1442. $english_mail = $this->randomEmail();
  1443. $spanish_mail = $this->randomEmail();
  1444. $spanish_mail2 = $this->randomEmail();
  1445. $tid = $this->getRandomNewsletter();
  1446. simplenews_subscribe_user($english_mail, $tid, FALSE, 'english', 'en');
  1447. simplenews_subscribe_user($spanish_mail, $tid, FALSE, 'spanish', 'es');
  1448. simplenews_subscribe_user($spanish_mail2, $tid, FALSE, 'spanish', 'es');
  1449. // Translate category.
  1450. $vocabulary = taxonomy_vocabulary_machine_name_load('newsletter');
  1451. $vocabulary->i18n_mode = I18N_MODE_LOCALIZE;
  1452. taxonomy_vocabulary_save($vocabulary);
  1453. drupal_static_reset('i18n_taxonomy_vocabulary_mode');
  1454. // Refresh strings.
  1455. // @todo: simplenews_category_save() should probably take care of this.
  1456. // Currently done separately in simplenews_admin_category_form_submit()
  1457. // for the admin UI.
  1458. $tid = $this->getRandomNewsletter();
  1459. $term = taxonomy_term_load($tid);
  1460. taxonomy_term_save($term);
  1461. // Translate term to spanish.
  1462. list($textgroup, $context) = i18n_string_context(array('taxonomy', 'term', $tid, 'name'));
  1463. i18n_string_textgroup($textgroup)->update_translation($context, 'es', $es_name = $this->randomName());
  1464. // Enable translation for newsletters.
  1465. $edit = array(
  1466. 'language_content_type' => TRANSLATION_ENABLED,
  1467. );
  1468. $this->drupalPost('admin/structure/types/manage/simplenews', $edit, t('Save content type'));
  1469. // Create a Newsletter including a translation.
  1470. $english = array(
  1471. 'title' => $this->randomName(),
  1472. 'language' => 'en',
  1473. 'body[und][0][value]' => 'Link to node: [node:url]',
  1474. );
  1475. $this->drupalPost('node/add/simplenews', $english, ('Save'));
  1476. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  1477. $english_node = node_load($matches[1]);
  1478. $this->clickLink(t('Translate'));
  1479. $this->clickLink(t('add translation'));
  1480. $spanish = array(
  1481. 'title' => $this->randomName(),
  1482. );
  1483. $this->drupalPost(NULL, $spanish, ('Save'));
  1484. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  1485. $spanish_node = node_load($matches[1]);
  1486. entity_get_controller('node')->resetCache();
  1487. $english_node = node_load($english_node->nid);
  1488. // Verify redirecation to source.
  1489. $this->clickLink(t('Newsletter'));
  1490. $this->assertText(t('This newsletter issue is part of a translation set. Sending this set is controlled from the translation source newsletter.'));
  1491. $this->clickLink(t('translation source newsletter'));
  1492. $this->assertText($english_node->title);
  1493. // Send newsletter.
  1494. $this->clickLink(t('Newsletter'));
  1495. $edit = array(
  1496. 'simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW,
  1497. );
  1498. $this->drupalPost(NULL, $edit, t('Submit'));
  1499. simplenews_cron();
  1500. $this->assertEqual(3, count($this->drupalGetMails()));
  1501. $category = simplenews_category_load($this->getRandomNewsletter());
  1502. $languages = language_list();
  1503. foreach ($this->drupalGetMails() as $mail) {
  1504. if ($mail['to'] == $english_mail) {
  1505. $this->assertEqual('en', $mail['language']);
  1506. $this->assertEqual('[' . $category->name . '] ' . $english_node->title, $mail['subject']);
  1507. $node_url = url('node/' . $english_node->nid, array('language' => $languages['en'], 'absolute' => TRUE));
  1508. }
  1509. elseif ($mail['to'] == $spanish_mail || $mail['to'] == $spanish_mail2) {
  1510. $this->assertEqual('es', $mail['language']);
  1511. $this->assertEqual('[' . $es_name . '] ' . $spanish_node->title, $mail['subject']);
  1512. $node_url = url('node/' . $spanish_node->nid, array('language' => $languages['es'], 'absolute' => TRUE));
  1513. }
  1514. else {
  1515. $this->fail(t('Mail not sent to expected recipient'));
  1516. }
  1517. // Verify that the link is in the correct language.
  1518. $this->assertTrue(strpos($mail['body'], $node_url) !== FALSE);
  1519. }
  1520. // Verify sent subscriber count for each node.
  1521. $newsletter = simplenews_newsletter_load($english_node->nid);
  1522. $this->assertEqual(1, $newsletter->sent_subscriber_count, 'subscriber count is correct for english');
  1523. $newsletter = simplenews_newsletter_load($spanish_node->nid);
  1524. $this->assertEqual(2, $newsletter->sent_subscriber_count, 'subscriber count is correct for spanish');
  1525. // Make sure the language of a node can be changed.
  1526. $english = array(
  1527. 'title' => $this->randomName(),
  1528. 'language' => 'en',
  1529. 'body[und][0][value]' => 'Link to node: [node:url]',
  1530. );
  1531. $this->drupalPost('node/add/simplenews', $english, ('Save'));
  1532. $this->clickLink(t('Edit'));
  1533. $edit = array(
  1534. 'language' => 'es',
  1535. );
  1536. $this->drupalPost(NULL, $edit, t('Save'));
  1537. }
  1538. /**
  1539. * Set up configuration for multiple languages.
  1540. *
  1541. * Copied from Drupali18nTestCase::setUpLanguages().
  1542. */
  1543. function setUpLanguages($admin_permissions = array()) {
  1544. // Add languages.
  1545. $this->default_language = 'en';
  1546. $this->secondary_language = 'es';
  1547. $this->addLanguage($this->default_language);
  1548. $this->addLanguage($this->secondary_language);
  1549. // Enable URL language detection and selection to make the language switcher
  1550. // block appear.
  1551. $edit = array('language[enabled][locale-url]' => TRUE);
  1552. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  1553. $this->assertRaw(t('Language negotiation configuration saved.'), t('URL language detection enabled.'));
  1554. $this->drupalGet('admin/config/regional/language/configure');
  1555. drupal_static_reset('locale_url_outbound_alter');
  1556. drupal_static_reset('language_list');
  1557. }
  1558. }
  1559. class SimpleNewsUpgradePathTestCase extends UpgradePathTestCase {
  1560. public function setUp() {
  1561. parent::setUp();
  1562. // Use the test mail class instead of the default mail handler class.
  1563. $this->variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
  1564. }
  1565. public function prepareUpgradePath() {
  1566. // Delete everything except taxnomy and simplenews from system to
  1567. // prevent their update functions to be run.
  1568. $this->uninstallModulesExcept(array('taxonomy', 'simplenews'));
  1569. // Disable simplenews, the update hooks will be executed anyway.
  1570. db_update('system')
  1571. ->fields(array(
  1572. 'status' => 0,
  1573. ))
  1574. ->condition('name', 'simplenews')
  1575. ->execute();
  1576. }
  1577. public function assertUpgradePath() {
  1578. // Enable simplenews.
  1579. $edit = array(
  1580. 'modules[Mail][simplenews][enable]' => 1,
  1581. );
  1582. $this->drupalPost('admin/modules', $edit, t('Save configuration'));
  1583. // Attempt to subscribe a mail address.
  1584. $mail = 'new@example.org';
  1585. $tid = 1;
  1586. module_load_include('module', 'simplenews');
  1587. simplenews_subscribe_user($mail, $tid, FALSE);
  1588. $this->drupalGet('admin/config/services/simplenews');
  1589. $this->assertText('Drupal 6 newsletter');
  1590. $this->assertText('Test');
  1591. $this->drupalGet('admin/people/simplenews');
  1592. $this->assertText('another@example.org');
  1593. $this->assertText($mail);
  1594. $this->drupalGet('admin/structure/taxonomy/newsletter');
  1595. // Check simplenews content type.
  1596. $this->drupalGet('admin/structure/types/manage/simplenews');
  1597. $this->assertFieldChecked('edit-simplenews-content-type');
  1598. $this->drupalGet('admin/structure/types/manage/simplenews/fields');
  1599. $this->drupalGet('node/add/simplenews');
  1600. $this->assertText('Newsletter');
  1601. $this->assertText('Drupal 6 newsletter');
  1602. // Check category field
  1603. $this->assertEqual(variable_get('simplenews_category_field'), 'taxonomy_vocabulary_1');
  1604. $this->assertTrue(field_info_instance('node', 'taxonomy_vocabulary_1', 'simplenews'));
  1605. // Create an issue.
  1606. $edit = array(
  1607. 'title' => $this->randomName(),
  1608. 'taxonomy_vocabulary_1[und]' => 1,
  1609. );
  1610. $this->drupalPost(NULL, $edit, ('Save'));
  1611. // Send newsletter.
  1612. $this->clickLink(t('Newsletter'));
  1613. $this->drupalPost(NULL, array(), t('Submit'));
  1614. // TODO: Maybe it would be bether to retreive the nid of the created node instead of hard code it.
  1615. $this->assertEqual(1, db_query('SELECT tid FROM {simplenews_newsletter} WHERE nid = :nid', array(':nid' => 2))->fetchField(), 'There is an issue associated to the correct newsletter category');
  1616. // @todo Mails are not correctly returned
  1617. // $mails = $this->drupalGetMails();
  1618. // debug($mails);
  1619. // $this->assertEqual('simplenews_test', $mails[0]['id']);
  1620. // $this->assertEqual('user@example.com', $mails[0]['to']);
  1621. // $this->assertEqual(t('[Drupal newsletter] @title', array('@title' => $edit['title'])), $mails[0]['subject']);
  1622. // Make sure that new categories can be created.
  1623. $edit = array(
  1624. 'name' => $this->randomName(),
  1625. );
  1626. $this->drupalPost('admin/config/services/simplenews/add', $edit, t('Save'));
  1627. $this->assertResponse(200);
  1628. $this->assertText($edit['name']);
  1629. }
  1630. }
  1631. /**
  1632. * Upgrade test from 6.x-1.x
  1633. */
  1634. class SimpleNewsUpgradePath61TestCase extends SimpleNewsUpgradePathTestCase {
  1635. public static function getInfo() {
  1636. return array(
  1637. 'name' => 'Simplenews 6.x-1.x upgrade path',
  1638. 'description' => 'Simplenews 6.x-1.x upgrade path tests.',
  1639. 'group' => 'Simplenews',
  1640. );
  1641. }
  1642. public function setUp() {
  1643. // Path to the database dump files.
  1644. $this->databaseDumpFiles = array(
  1645. drupal_get_path('module', 'simplenews') . '/tests/d6_simplenews_61.php',
  1646. );
  1647. parent::setUp();
  1648. }
  1649. /**
  1650. * Test a successful upgrade.
  1651. */
  1652. public function testSimplenewsUpgrade() {
  1653. $this->prepareUpgradePath();
  1654. $this->assertTrue($this->performUpgrade(), t('Upgraded successfully.'));
  1655. $this->assertUpgradePath();
  1656. }
  1657. }
  1658. /**
  1659. * Upgrade test from 6.x-2.x
  1660. */
  1661. class SimpleNewsUpgradePath62TestCase extends SimpleNewsUpgradePathTestCase {
  1662. public static function getInfo() {
  1663. return array(
  1664. 'name' => 'Simplenews 6.x-2.x upgrade path',
  1665. 'description' => 'Simplenews 6.x-2.x upgrade path tests.',
  1666. 'group' => 'Simplenews',
  1667. );
  1668. }
  1669. public function setUp() {
  1670. // Path to the database dump files.
  1671. $this->databaseDumpFiles = array(
  1672. drupal_get_path('module', 'simplenews') . '/tests/d6_simplenews_62.php',
  1673. );
  1674. parent::setUp();
  1675. // Use the test mail class instead of the default mail handler class.
  1676. $this->variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
  1677. }
  1678. /**
  1679. * Test a successful upgrade.
  1680. */
  1681. public function testSimplenewsUpgrade() {
  1682. $this->prepareUpgradePath();
  1683. $this->assertTrue($this->performUpgrade(), t('Upgraded successfully.'));
  1684. $this->assertUpgradePath();
  1685. }
  1686. }
  1687. /**
  1688. * Test cases for creating and sending newsletters.
  1689. */
  1690. class SimplenewsSendTestCase extends SimplenewsTestCase {
  1691. /**
  1692. * Implementation of getInfo().
  1693. */
  1694. function getInfo() {
  1695. return array(
  1696. 'name' => t('Sending newsletters'),
  1697. 'description' => t('Creating and sending of newsletters, different send processes (with/without cron, send on publish)'),
  1698. 'group' => t('Simplenews'),
  1699. );
  1700. }
  1701. function setUp() {
  1702. parent::setUp();
  1703. $this->user = $this->drupalCreateUser(array('administer newsletters', 'send newsletter', 'administer nodes', 'administer simplenews subscriptions', 'create simplenews content', 'edit any simplenews content', 'view own unpublished content', 'delete any simplenews content'));
  1704. $this->drupalLogin($this->user);
  1705. // Subscribe a few users.
  1706. $this->setUpSubscribers(5);
  1707. }
  1708. /**
  1709. * Creates and sends a node using the API.
  1710. */
  1711. function testProgrammaticNewsletter() {
  1712. // Create a very basic node.
  1713. $node = new stdClass();
  1714. $node->type = 'simplenews';
  1715. $node->title = $this->randomName();
  1716. $node->uid = 0;
  1717. $node->status = 1;
  1718. $node->language = LANGUAGE_NONE;
  1719. $node->field_simplenews_term[LANGUAGE_NONE][0]['tid'] = $this->getRandomNewsletter();
  1720. node_save($node);
  1721. // Send the node.
  1722. simplenews_add_node_to_spool($node);
  1723. // Send mails.
  1724. simplenews_mail_spool();
  1725. simplenews_clear_spool();
  1726. // Update sent status for newsletter admin panel.
  1727. simplenews_send_status_update();
  1728. // Verify mails.
  1729. $mails = $this->drupalGetMails();
  1730. $this->assertEqual(5, count($mails), t('All mails were sent.'));
  1731. foreach ($mails as $mail) {
  1732. $this->assertEqual($mail['subject'], '[Drupal newsletter] ' . $node->title, t('Mail has correct subject'));
  1733. $this->assertTrue(isset($this->subscribers[$mail['to']]), t('Found valid recipient'));
  1734. unset($this->subscribers[$mail['to']]);
  1735. }
  1736. $this->assertEqual(0, count($this->subscribers), t('all subscribers have been received a mail'));
  1737. // Create another node.
  1738. $node = new stdClass();
  1739. $node->type = 'simplenews';
  1740. $node->title = $this->randomName();
  1741. $node->uid = 0;
  1742. $node->status = 1;
  1743. $node->language = LANGUAGE_NONE;
  1744. $node->field_simplenews_term[LANGUAGE_NONE][0]['tid'] = $this->getRandomNewsletter();
  1745. node_save($node);
  1746. // Send the node.
  1747. simplenews_add_node_to_spool($node);
  1748. // Make sure that they have been added.
  1749. $this->assertEqual(simplenews_count_spool(), 5);
  1750. // Mark them as pending, fake a currently running send process.
  1751. $this->assertEqual(count(simplenews_get_spool(2)), 2);
  1752. // Those two should be excluded from the count now.
  1753. $this->assertEqual(simplenews_count_spool(), 3);
  1754. // Get two additional spool entries.
  1755. $this->assertEqual(count(simplenews_get_spool(2)), 2);
  1756. // Now only one should be returned by the count.
  1757. $this->assertEqual(simplenews_count_spool(), 1);
  1758. }
  1759. /**
  1760. * Send a newsletter using cron.
  1761. */
  1762. function testSendNowNoCron() {
  1763. // Disable cron.
  1764. variable_set('simplenews_use_cron', FALSE);
  1765. // Verify that the newsletter settings are shown.
  1766. $this->drupalGet('node/add/simplenews');
  1767. $this->assertText(t('Newsletter category'));
  1768. $edit = array(
  1769. 'title' => $this->randomName(),
  1770. );
  1771. $this->drupalPost(NULL, $edit, ('Save'));
  1772. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  1773. $node = node_load($matches[1]);
  1774. $this->clickLink(t('Newsletter'));
  1775. $this->assertText(t('Send one test newsletter to the test address'));
  1776. $this->assertText(t('Send newsletter'));
  1777. $this->assertNoText(t('Send newsletter when published'), t('Send on publish is not shown for published nodes.'));
  1778. // Verify state.
  1779. $newsletter = simplenews_newsletter_load($node->nid);
  1780. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Newsletter not sent yet.'));
  1781. // Send now.
  1782. $this->drupalPost(NULL, array('simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW), t('Submit'));
  1783. // Verify state.
  1784. $newsletter = simplenews_newsletter_load($node->nid);
  1785. $this->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $newsletter->status, t('Newsletter sending finished'));
  1786. // Verify mails.
  1787. $mails = $this->drupalGetMails();
  1788. $this->assertEqual(5, count($mails), t('All mails were sent.'));
  1789. foreach ($mails as $mail) {
  1790. $this->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], t('Mail has correct subject'));
  1791. $this->assertTrue(isset($this->subscribers[$mail['to']]), t('Found valid recipient'));
  1792. unset($this->subscribers[$mail['to']]);
  1793. }
  1794. $this->assertEqual(0, count($this->subscribers), t('all subscribers have been received a mail'));
  1795. $newsletter = simplenews_newsletter_load($node->nid);
  1796. $this->assertEqual(5, $newsletter->sent_subscriber_count, 'subscriber count is correct');
  1797. }
  1798. /**
  1799. * Send a newsletter using cron.
  1800. */
  1801. function testSendMultipleNoCron() {
  1802. // Disable cron.
  1803. variable_set('simplenews_use_cron', FALSE);
  1804. // Verify that the newsletter settings are shown.
  1805. $nodes = array();
  1806. for ($i = 0; $i < 3; $i++) {
  1807. $this->drupalGet('node/add/simplenews');
  1808. $this->assertText(t('Newsletter category'));
  1809. $edit = array(
  1810. 'title' => $this->randomName(),
  1811. // The last newsletter shouldn't be published.
  1812. 'status' => $i != 2,
  1813. );
  1814. $this->drupalPost(NULL, $edit, ('Save'));
  1815. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  1816. $nodes[] = node_load($matches[1]);
  1817. // Verify state.
  1818. $newsletter = simplenews_newsletter_load($matches[1]);
  1819. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Newsletter not sent yet.'));
  1820. }
  1821. // Send the first and last newsletter on the newsletter overview.
  1822. list ($first, $second, $unpublished) = $nodes;
  1823. $edit = array(
  1824. 'issues[' . $first->nid . ']' => $first->nid,
  1825. 'issues[' . $unpublished->nid . ']' => $unpublished->nid,
  1826. 'operation' => 'activate',
  1827. );
  1828. $this->drupalPost('admin/content/simplenews', $edit, t('Update'));
  1829. $this->assertText(t('Sent the following newsletters: @title.', array('@title' => $first->title)));
  1830. $this->assertText(t('Newsletter @title is unpublished and will be sent on publish.', array('@title' => $unpublished->title)));
  1831. // Verify states.
  1832. $newsletter = simplenews_newsletter_load($first->nid);
  1833. $this->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $newsletter->status, t('First Newsletter sending finished'));
  1834. $newsletter = simplenews_newsletter_load($second->nid);
  1835. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Second Newsletter not sent'));
  1836. $newsletter = simplenews_newsletter_load($unpublished->nid);
  1837. $this->assertEqual(SIMPLENEWS_STATUS_SEND_PUBLISH, $newsletter->status, t('Newsletter set to send on publish'));
  1838. // Verify mails.
  1839. $mails = $this->drupalGetMails();
  1840. $this->assertEqual(5, count($mails), t('All mails were sent.'));
  1841. foreach ($mails as $mail) {
  1842. $this->assertEqual($mail['subject'], '[Drupal newsletter] ' . $first->title, t('Mail has correct subject'));
  1843. $this->assertTrue(isset($this->subscribers[$mail['to']]), t('Found valid recipient'));
  1844. unset($this->subscribers[$mail['to']]);
  1845. }
  1846. $this->assertEqual(0, count($this->subscribers), t('all subscribers have been received a mail'));
  1847. }
  1848. /**
  1849. * Send a newsletter using cron and a low throttle.
  1850. */
  1851. function testSendNowCronThrottle() {
  1852. variable_set('simplenews_throttle', 3);
  1853. // Verify that the newsletter settings are shown.
  1854. $this->drupalGet('node/add/simplenews');
  1855. $this->assertText(t('Newsletter category'));
  1856. $edit = array(
  1857. 'title' => $this->randomName(),
  1858. );
  1859. $this->drupalPost(NULL, $edit, ('Save'));
  1860. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  1861. $node = node_load($matches[1]);
  1862. $this->clickLink(t('Newsletter'));
  1863. $this->assertText(t('Send one test newsletter to the test address'));
  1864. $this->assertText(t('Send newsletter'));
  1865. $this->assertNoText(t('Send newsletter when published'), t('Send on publish is not shown for published nodes.'));
  1866. // Verify state.
  1867. $newsletter = simplenews_newsletter_load($node->nid);
  1868. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Newsletter not sent yet.'));
  1869. // Send now.
  1870. $this->drupalPost(NULL, array('simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW), t('Submit'));
  1871. // Verify state.
  1872. $newsletter = simplenews_newsletter_load($node->nid);
  1873. $this->assertEqual(SIMPLENEWS_STATUS_SEND_PENDING, $newsletter->status, t('Newsletter sending pending.'));
  1874. // Verify that no mails have been sent yet.
  1875. $mails = $this->drupalGetMails();
  1876. $this->assertEqual(0, count($mails), t('No mails were sent yet.'));
  1877. $spooled = db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
  1878. $this->assertEqual(5, $spooled, t('5 mails have been added to the mail spool'));
  1879. // Run cron for the first time.
  1880. simplenews_cron();
  1881. // Verify state.
  1882. $newsletter = simplenews_newsletter_load($node->nid);
  1883. $this->assertEqual(SIMPLENEWS_STATUS_SEND_PENDING, $newsletter->status, t('Newsletter sending pending.'));
  1884. $this->assertEqual(3, $newsletter->sent_subscriber_count, 'subscriber count is correct');
  1885. $spooled = db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
  1886. $this->assertEqual(2, $spooled, t('2 mails remaining in spool.'));
  1887. // Run cron for the second time.
  1888. simplenews_cron();
  1889. // Verify state.
  1890. $newsletter = simplenews_newsletter_load($node->nid);
  1891. $this->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $newsletter->status, t('Newsletter sending finished.'));
  1892. $spooled = db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
  1893. $this->assertEqual(0, $spooled, t('No mails remaining in spool.'));
  1894. // Verify mails.
  1895. $mails = $this->drupalGetMails();
  1896. $this->assertEqual(5, count($mails), t('All mails were sent.'));
  1897. foreach ($mails as $mail) {
  1898. $this->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], t('Mail has correct subject'));
  1899. $this->assertTrue(isset($this->subscribers[$mail['to']]), t('Found valid recipient'));
  1900. unset($this->subscribers[$mail['to']]);
  1901. }
  1902. $this->assertEqual(0, count($this->subscribers), t('all subscribers have been received a mail'));
  1903. $newsletter = simplenews_newsletter_load($node->nid);
  1904. $this->assertEqual(5, $newsletter->sent_subscriber_count, 'subscriber count is correct');
  1905. }
  1906. /**
  1907. * Send a newsletter without using cron.
  1908. */
  1909. function testSendNowCron() {
  1910. // Verify that the newsletter settings are shown.
  1911. $this->drupalGet('node/add/simplenews');
  1912. $this->assertText(t('Newsletter category'));
  1913. $edit = array(
  1914. 'title' => $this->randomName(),
  1915. );
  1916. // Try preview first.
  1917. $this->drupalPost(NULL, $edit, t('Preview'));
  1918. // Then save.
  1919. $this->drupalPost(NULL, array(), t('Save'));
  1920. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  1921. $node = node_load($matches[1]);
  1922. $this->clickLink(t('Newsletter'));
  1923. $this->assertText(t('Send one test newsletter to the test address'));
  1924. $this->assertText(t('Send newsletter'));
  1925. $this->assertNoText(t('Send newsletter when published'), t('Send on publish is not shown for published nodes.'));
  1926. // Verify state.
  1927. $newsletter = simplenews_newsletter_load($node->nid);
  1928. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Newsletter not sent yet.'));
  1929. // Send now.
  1930. $this->drupalPost(NULL, array('simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW), t('Submit'));
  1931. // Verify state.
  1932. $newsletter = simplenews_newsletter_load($node->nid);
  1933. $this->assertEqual(SIMPLENEWS_STATUS_SEND_PENDING, $newsletter->status, t('Newsletter sending pending.'));
  1934. // Verify that no mails have been sent yet.
  1935. $mails = $this->drupalGetMails();
  1936. $this->assertEqual(0, count($mails), t('No mails were sent yet.'));
  1937. $spooled = db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
  1938. $this->assertEqual(5, $spooled, t('5 mails have been added to the mail spool'));
  1939. // Check warning message on node edit form.
  1940. $this->clickLink(t('Edit'));
  1941. $this->assertText(t('This newsletter issue is currently being sent. Any changes will be reflected in the e-mails which have not been sent yet.'));
  1942. // Run cron.
  1943. simplenews_cron();
  1944. // Verify state.
  1945. $newsletter = simplenews_newsletter_load($node->nid);
  1946. $this->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $newsletter->status, t('Newsletter sending finished.'));
  1947. $spooled = db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
  1948. $this->assertEqual(0, $spooled, t('No mails remaining in spool.'));
  1949. // Verify mails.
  1950. $mails = $this->drupalGetMails();
  1951. $this->assertEqual(5, count($mails), t('All mails were sent.'));
  1952. foreach ($mails as $mail) {
  1953. $this->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], t('Mail has correct subject'));
  1954. $this->assertTrue(isset($this->subscribers[$mail['to']]), t('Found valid recipient'));
  1955. unset($this->subscribers[$mail['to']]);
  1956. }
  1957. $this->assertEqual(0, count($this->subscribers), t('all subscribers have been received a mail'));
  1958. }
  1959. /**
  1960. * Send a newsletter on publish without using cron.
  1961. */
  1962. function testSendPublishNoCron() {
  1963. // Disable cron.
  1964. variable_set('simplenews_use_cron', FALSE);
  1965. // Verify that the newsletter settings are shown.
  1966. $this->drupalGet('node/add/simplenews');
  1967. $this->assertText(t('Newsletter category'));
  1968. $edit = array(
  1969. 'title' => $this->randomName(),
  1970. 'status' => FALSE,
  1971. );
  1972. $this->drupalPost(NULL, $edit, ('Save'));
  1973. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  1974. $node = node_load($matches[1]);
  1975. $this->clickLink(t('Newsletter'));
  1976. $this->assertText(t('Send one test newsletter to the test address'));
  1977. $this->assertText(t('Send newsletter when published'), t('Send on publish is shown'));
  1978. // Verify state.
  1979. $newsletter = simplenews_newsletter_load($node->nid);
  1980. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Newsletter not sent yet.'));
  1981. // Send now.
  1982. $this->drupalPost(NULL, array('simplenews[send]' => SIMPLENEWS_COMMAND_SEND_PUBLISH), t('Submit'));
  1983. // Verify state.
  1984. $newsletter = simplenews_newsletter_load($node->nid);
  1985. $this->assertEqual(SIMPLENEWS_STATUS_SEND_PUBLISH, $newsletter->status, t('Newsletter set up for sending on publish.'));
  1986. $this->clickLink(t('Edit'));
  1987. $update = array(
  1988. 'status' => TRUE,
  1989. );
  1990. $this->drupalPost(NULL, $update, t('Save'));
  1991. // Send on publish does not send immediately.
  1992. simplenews_mail_attempt_immediate_send(array(), FALSE);
  1993. // Verify state.
  1994. $newsletter = simplenews_newsletter_load($node->nid);
  1995. $this->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $newsletter->status, t('Newsletter sending finished'));
  1996. // @todo test sent subscriber count.
  1997. // Verify mails.
  1998. $mails = $this->drupalGetMails();
  1999. $this->assertEqual(5, count($mails), t('All mails were sent.'));
  2000. foreach ($mails as $mail) {
  2001. $this->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], t('Mail has correct subject'));
  2002. $this->assertTrue(isset($this->subscribers[$mail['to']]), t('Found valid recipient'));
  2003. unset($this->subscribers[$mail['to']]);
  2004. }
  2005. $this->assertEqual(0, count($this->subscribers), t('all subscribers have been received a mail'));
  2006. }
  2007. function testUpdateNewsletter() {
  2008. // Create a second category.
  2009. $this->drupalGet('admin/config/services/simplenews');
  2010. $this->clickLink(t('Add newsletter category'));
  2011. $edit = array(
  2012. 'name' => $this->randomName(),
  2013. 'description' => $this->randomString(20),
  2014. );
  2015. $this->drupalPost(NULL, $edit, t('Save'));
  2016. $this->drupalGet('node/add/simplenews');
  2017. $this->assertText(t('Newsletter category'));
  2018. $edit = array(
  2019. 'title' => $this->randomName(),
  2020. // @todo avoid hardcoding the term id.
  2021. 'field_simplenews_term[und]' => 1,
  2022. );
  2023. $this->drupalPost(NULL, $edit, ('Save'));
  2024. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created.');
  2025. $node = node_load($matches[1]);
  2026. // Verify newsletter.
  2027. $newsletter = simplenews_newsletter_load($node->nid);
  2028. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Newsletter sending not started.'));
  2029. $this->assertEqual(1, $newsletter->tid, t('Newsletter has tid 1'));
  2030. $this->clickLink(t('Edit'));
  2031. $update = array(
  2032. 'field_simplenews_term[und]' => 2,
  2033. );
  2034. $this->drupalPost(NULL, $update, t('Save'));
  2035. // Verify newsletter.
  2036. $newsletter = simplenews_newsletter_load($node->nid);
  2037. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Newsletter sending not started.'));
  2038. $this->assertEqual(2, $newsletter->tid, t('Newsletter has tid 2.'));
  2039. }
  2040. /**
  2041. * Create a newsletter, send mails and then delete.
  2042. */
  2043. function testDelete() {
  2044. // Verify that the newsletter settings are shown.
  2045. $this->drupalGet('node/add/simplenews');
  2046. $this->assertText(t('Newsletter category'));
  2047. // Prevent deleting the mail spool entries automatically.
  2048. variable_set('simplenews_spool_expire', 1);
  2049. $edit = array(
  2050. 'title' => $this->randomName(),
  2051. );
  2052. $this->drupalPost(NULL, $edit, ('Save'));
  2053. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  2054. $node = node_load($matches[1]);
  2055. $this->clickLink(t('Newsletter'));
  2056. $this->assertText(t('Send one test newsletter to the test address'));
  2057. $this->assertText(t('Send newsletter'));
  2058. $this->assertNoText(t('Send newsletter when published'), t('Send on publish is not shown for published nodes.'));
  2059. // Verify state.
  2060. $newsletter = simplenews_newsletter_load($node->nid);
  2061. $this->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $newsletter->status, t('Newsletter not sent yet.'));
  2062. // Send now.
  2063. $this->drupalPost(NULL, array('simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW), t('Submit'));
  2064. // Verify state.
  2065. $newsletter = simplenews_newsletter_load($node->nid);
  2066. $this->assertEqual(SIMPLENEWS_STATUS_SEND_PENDING, $newsletter->status, t('Newsletter sending pending.'));
  2067. $spooled = db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
  2068. $this->assertEqual(5, $spooled, t('5 mails remaining in spool.'));
  2069. // Verify that deleting isn't possible right now.
  2070. $this->clickLink(t('Edit'));
  2071. $this->assertText(t("You can't delete this newsletter because it has not been sent to all its subscribers."));
  2072. $this->assertNoText(t('Delete'));
  2073. // Send mails.
  2074. simplenews_cron();
  2075. // Verify state.
  2076. $newsletter = simplenews_newsletter_load($node->nid);
  2077. $this->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $newsletter->status, t('Newsletter sending finished'));
  2078. $spooled = db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
  2079. $this->assertEqual(5, $spooled, t('Mails are kept in simplenews_mail_spool after being sent.'));
  2080. // Verify mails.
  2081. $mails = $this->drupalGetMails();
  2082. $this->assertEqual(5, count($mails), t('All mails were sent.'));
  2083. foreach ($mails as $mail) {
  2084. $this->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], t('Mail has correct subject'));
  2085. $this->assertTrue(isset($this->subscribers[$mail['to']]), t('Found valid recipient'));
  2086. unset($this->subscribers[$mail['to']]);
  2087. }
  2088. $this->assertEqual(0, count($this->subscribers), t('all subscribers have been received a mail'));
  2089. // Update timestamp to simulate pending lock expiration.
  2090. db_update('simplenews_mail_spool')
  2091. ->fields(array(
  2092. 'timestamp' => simplenews_get_expiration_time() - 1,
  2093. ))
  2094. ->execute();
  2095. // Verify that kept mail spool rows are not re-sent.
  2096. simplenews_cron();
  2097. simplenews_get_spool();
  2098. $mails = $this->drupalGetMails();
  2099. $this->assertEqual(5, count($mails), t('No additional mails have been sent.'));
  2100. // Now delete.
  2101. $this->clickLink(t('Edit'));
  2102. $this->drupalPost(NULL, array(), t('Delete'));
  2103. $this->drupalPost(NULL, array(), t('Delete'));
  2104. // Verify.
  2105. $newsletter = simplenews_newsletter_load($node->nid);
  2106. $this->assertFalse($newsletter);
  2107. $spooled = db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField();
  2108. $this->assertEqual(0, $spooled, t('No mails remaining in spool.'));
  2109. }
  2110. }
  2111. /**
  2112. * Test cases for creating and sending newsletters.
  2113. */
  2114. class SimplenewsSourceTestCase extends SimplenewsTestCase {
  2115. /**
  2116. * Implementation of getInfo().
  2117. */
  2118. function getInfo() {
  2119. return array(
  2120. 'name' => t('Source tests'),
  2121. 'description' => t('Tests for the new source interfaces and concepts.'),
  2122. 'group' => t('Simplenews'),
  2123. );
  2124. }
  2125. function setUp() {
  2126. parent::setUp();
  2127. // Create the filtered_html text format.
  2128. $filtered_html_format = array(
  2129. 'format' => 'filtered_html',
  2130. 'name' => 'Filtered HTML',
  2131. 'weight' => 0,
  2132. 'filters' => array(
  2133. // URL filter.
  2134. 'filter_url' => array(
  2135. 'weight' => 0,
  2136. 'status' => 1,
  2137. ),
  2138. // HTML filter.
  2139. 'filter_html' => array(
  2140. 'weight' => 1,
  2141. 'status' => 1,
  2142. ),
  2143. // Line break filter.
  2144. 'filter_autop' => array(
  2145. 'weight' => 2,
  2146. 'status' => 1,
  2147. ),
  2148. // HTML corrector filter.
  2149. 'filter_htmlcorrector' => array(
  2150. 'weight' => 10,
  2151. 'status' => 1,
  2152. ),
  2153. ),
  2154. );
  2155. $filtered_html_format = (object) $filtered_html_format;
  2156. filter_format_save($filtered_html_format);
  2157. // Refresh permissions.
  2158. $this->checkPermissions(array(), TRUE);
  2159. $this->user = $this->drupalCreateUser(array('administer newsletters', 'send newsletter', 'administer nodes', 'administer simplenews subscriptions', 'create simplenews content', 'edit any simplenews content', 'view own unpublished content', 'delete any simplenews content', 'administer simplenews settings', filter_permission_name($filtered_html_format)));
  2160. $this->drupalLogin($this->user);
  2161. }
  2162. /**
  2163. * Tests that sending a minimal implementation of the source interface works.
  2164. */
  2165. function testSendMinimalSourceImplementation() {
  2166. // Create a basic plaintext test source and send it.
  2167. $plain_source = new SimplenewsSourceTest('plain');
  2168. simplenews_send_source($plain_source);
  2169. $mails = $this->drupalGetMails();
  2170. $mail = $mails[0];
  2171. // Assert resulting mail.
  2172. $this->assertEqual('simplenews_node', $mail['id']);
  2173. $this->assertEqual('simplenews', $mail['module']);
  2174. $this->assertEqual('node', $mail['key']);
  2175. $this->assertEqual($plain_source->getRecipient(), $mail['to']);
  2176. $this->assertEqual($plain_source->getFromFormatted(), $mail['from']);
  2177. $this->assertEqual($plain_source->getLanguage(), $mail['language']);
  2178. $this->assertTrue($mail['params']['plain']);
  2179. $this->assertFalse(isset($mail['params']['plaintext']));
  2180. $this->assertFalse(isset($mail['params']['attachments']));
  2181. $this->assertEqual($plain_source->getSubject(), $mail['subject']);
  2182. $this->assertTrue(strpos($mail['body'], 'the plain body') !== FALSE);
  2183. $this->assertTrue(strpos($mail['body'], 'the plain footer') !== FALSE);
  2184. $html_source = new SimplenewsSourceTest('html');
  2185. simplenews_send_source($html_source);
  2186. $mails = $this->drupalGetMails();
  2187. $mail = $mails[1];
  2188. // Assert resulting mail.
  2189. $this->assertEqual('simplenews_node', $mail['id']);
  2190. $this->assertEqual('simplenews', $mail['module']);
  2191. $this->assertEqual('node', $mail['key']);
  2192. $this->assertEqual($plain_source->getRecipient(), $mail['to']);
  2193. $this->assertEqual($plain_source->getFromFormatted(), $mail['from']);
  2194. $this->assertEqual($plain_source->getLanguage(), $mail['language']);
  2195. $this->assertEqual(NULL, $mail['params']['plain']);
  2196. $this->assertTrue(isset($mail['params']['plaintext']));
  2197. $this->assertTrue(strpos($mail['params']['plaintext'], 'the plain body') !== FALSE);
  2198. $this->assertTrue(strpos($mail['params']['plaintext'], 'the plain footer') !== FALSE);
  2199. $this->assertTrue(isset($mail['params']['attachments']));
  2200. $this->assertEqual('example://test.png', $mail['params']['attachments'][0]['uri']);
  2201. $this->assertEqual($plain_source->getSubject(), $mail['subject']);
  2202. $this->assertTrue(strpos($mail['body'], 'the body') !== FALSE);
  2203. $this->assertTrue(strpos($mail['body'], 'the footer') !== FALSE);
  2204. }
  2205. /**
  2206. * Test sending a newsletter to 100 recipients with caching enabled.
  2207. */
  2208. function testSendCaching() {
  2209. $this->setUpSubscribers(100);
  2210. // Enable build caching.
  2211. $edit = array(
  2212. 'simplenews_source_cache' => 'SimplenewsSourceCacheBuild',
  2213. );
  2214. $this->drupalPost('admin/config/services/simplenews/settings/mail', $edit, t('Save configuration'));
  2215. $edit = array(
  2216. 'title' => $this->randomName(),
  2217. 'body[und][0][value]' => "Mail token: <strong>[simplenews-subscriber:mail]</strong>",
  2218. );
  2219. $this->drupalPost('node/add/simplenews', $edit, ('Save'));
  2220. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  2221. $node = node_load($matches[1]);
  2222. // Add node to spool.
  2223. simplenews_add_node_to_spool($node);
  2224. // Unsubscribe one of the recipients to make sure that he doesn't receive
  2225. // the mail.
  2226. simplenews_unsubscribe_user(array_shift($this->subscribers), $this->getRandomNewsletter(), FALSE, 'test');
  2227. $before = microtime(TRUE);
  2228. simplenews_mail_spool();
  2229. $after = microtime(TRUE);
  2230. // Make sure that 99 mails have been sent.
  2231. $this->assertEqual(99, count($this->drupalGetMails()));
  2232. // Test that tokens are correctly replaced.
  2233. $tid = $this->getRandomNewsletter();
  2234. foreach (array_slice($this->drupalGetMails(), 0, 3) as $mail) {
  2235. // Make sure that the same mail was used in the body token as it has been
  2236. // sent to. Also verify that the mail is plaintext.
  2237. $this->assertTrue(strpos($mail['body'], '*' . $mail['to'] . '*') !== FALSE);
  2238. $this->assertFalse(strpos($mail['body'], '<strong>'));
  2239. // Make sure the body is only attached once.
  2240. $this->assertEqual(1, preg_match_all('/Mail token/', $mail['body'], $matches));
  2241. $this->assertTrue(strpos($mail['body'], t('Unsubscribe from this newsletter')));
  2242. // Make sure the mail has the correct unsubscribe hash.
  2243. $subscriber = simplenews_subscriber_load_by_mail($mail['to']);
  2244. $hash = simplenews_generate_hash($mail['to'], $subscriber->snid, $tid);
  2245. $this->assertTrue(strpos($mail['body'], $hash), 'Correct hash is used in footer');
  2246. $this->assertTrue(strpos($mail['headers']['List-Unsubscribe'], $hash), 'Correct hash is used in header');
  2247. }
  2248. // Report time. @todo: Find a way to actually do some assertions here.
  2249. $this->pass(t('Mails have been sent in @sec seconds with build caching enabled.', array('@sec' => round($after - $before, 3))));
  2250. }
  2251. /**
  2252. * Send a newsletter with the HTML format.
  2253. */
  2254. function testSendHTML() {
  2255. $this->setUpSubscribers(5);
  2256. // Use custom testing mail system to support HTML mails.
  2257. variable_set('mail_system', array('default-system' => 'SimplenewsHTMLTestingMailSystem'));
  2258. // Set the format to HTML.
  2259. $this->drupalGet('admin/config/services/simplenews');
  2260. $this->clickLink(t('edit newsletter category'));
  2261. $edit_category = array(
  2262. 'format' => 'html',
  2263. // Use umlaut to provoke mime encoding.
  2264. 'from_name' => 'Drupäl',
  2265. // @todo: This shouldn't be necessary, default value is missing. Probably
  2266. // should not be required.
  2267. 'from_address' => $this->randomEmail(),
  2268. // Request a confirmation receipt.
  2269. 'receipt' => TRUE,
  2270. );
  2271. $this->drupalPost(NULL, $edit_category, t('Save'));
  2272. $edit = array(
  2273. 'title' => $this->randomName(),
  2274. 'body[und][0][value]' => "Mail token: <strong>[simplenews-subscriber:mail]</strong>",
  2275. );
  2276. $this->drupalPost('node/add/simplenews', $edit, ('Save'));
  2277. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  2278. $node = node_load($matches[1]);
  2279. // Add node to spool.
  2280. simplenews_add_node_to_spool($node);
  2281. // Send mails.
  2282. simplenews_mail_spool();
  2283. // Make sure that 5 mails have been sent.
  2284. $this->assertEqual(5, count($this->drupalGetMails()));
  2285. // Test that tokens are correctly replaced.
  2286. foreach (array_slice($this->drupalGetMails(), 0, 3) as $mail) {
  2287. // Verify title.
  2288. $this->assertTrue(strpos($mail['body'], '<h2>' . $node->title . '</h2>') !== FALSE);
  2289. // Make sure that the same mail was used in the body token as it has been
  2290. // sent to.
  2291. $this->assertTrue(strpos($mail['body'], '<strong>' . $mail['to'] . '</strong>') !== FALSE);
  2292. // Make sure the body is only attached once.
  2293. $this->assertEqual(1, preg_match_all('/Mail token/', $mail['body'], $matches));
  2294. // Check the plaintext version.
  2295. $this->assertTrue(strpos($mail['params']['plaintext'], $mail['to']) !== FALSE);
  2296. $this->assertFalse(strpos($mail['params']['plaintext'], '<strong>'));
  2297. // Make sure the body is only attached once.
  2298. $this->assertEqual(1, preg_match_all('/Mail token/', $mail['params']['plaintext'], $matches));
  2299. // Make sure formatted address is properly encoded.
  2300. $from = '"' . addslashes(mime_header_encode($edit_category['from_name'])) . '" <' . $edit_category['from_address'] . '>';
  2301. $this->assertEqual($from, $mail['from']);
  2302. // And make sure it won't get encoded twice.
  2303. $this->assertEqual($from, mime_header_encode($mail['from']));
  2304. // @todo: Improve this check, there are currently two spaces, not sure
  2305. // where they are coming from.
  2306. $this->assertTrue(strpos($mail['body'], 'class="newsletter-footer"'));
  2307. // Verify receipt headers.
  2308. $this->assertEqual($mail['headers']['Disposition-Notification-To'], $edit_category['from_address']);
  2309. $this->assertEqual($mail['headers']['X-Confirm-Reading-To'], $edit_category['from_address']);
  2310. }
  2311. }
  2312. /**
  2313. * Send a newsletter with the category set to hidden.
  2314. */
  2315. function testSendHidden() {
  2316. $this->setUpSubscribers(5);
  2317. // Set the format to HTML.
  2318. $this->drupalGet('admin/config/services/simplenews');
  2319. $this->clickLink(t('edit newsletter category'));
  2320. $edit = array(
  2321. 'opt_inout' => 'hidden',
  2322. // @todo: This shouldn't be necessary.
  2323. 'from_address' => $this->randomEmail(),
  2324. );
  2325. $this->drupalPost(NULL, $edit, t('Save'));
  2326. $edit = array(
  2327. 'title' => $this->randomName(),
  2328. 'body[und][0][value]' => "Mail token: <strong>[simplenews-subscriber:mail]</strong>",
  2329. );
  2330. $this->drupalPost('node/add/simplenews', $edit, ('Save'));
  2331. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  2332. $node = node_load($matches[1]);
  2333. // Add node to spool.
  2334. simplenews_add_node_to_spool($node);
  2335. // Send mails.
  2336. simplenews_mail_spool();
  2337. // Make sure that 5 mails have been sent.
  2338. $this->assertEqual(5, count($this->drupalGetMails()));
  2339. // Test that tokens are correctly replaced.
  2340. foreach (array_slice($this->drupalGetMails(), 0, 3) as $mail) {
  2341. // Verify the footer is not displayed for hidden newsletters.
  2342. $this->assertFalse(strpos($mail['body'], t('Unsubscribe from this newsletter')));
  2343. }
  2344. }
  2345. /**
  2346. * Test with disabled caching.
  2347. */
  2348. function testSendNoCaching() {
  2349. $this->setUpSubscribers(100);
  2350. // Disable caching.
  2351. $edit = array(
  2352. 'simplenews_source_cache' => 'SimplenewsSourceCacheNone',
  2353. );
  2354. $this->drupalPost('admin/config/services/simplenews/settings/mail', $edit, t('Save configuration'));
  2355. $edit = array(
  2356. 'title' => $this->randomName(),
  2357. 'body[und][0][value]' => "Mail token: <strong>[simplenews-subscriber:mail]</strong>",
  2358. );
  2359. $this->drupalPost('node/add/simplenews', $edit, ('Save'));
  2360. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  2361. $node = node_load($matches[1]);
  2362. // Add node to spool.
  2363. simplenews_add_node_to_spool($node);
  2364. $before = microtime(TRUE);
  2365. simplenews_mail_spool();
  2366. $after = microtime(TRUE);
  2367. // Make sure that 100 mails have been sent.
  2368. $this->assertEqual(100, count($this->drupalGetMails()));
  2369. // Test that tokens are correctly replaced.
  2370. foreach (array_slice($this->drupalGetMails(), 0, 3) as $mail) {
  2371. // Make sure that the same mail was used in the body token as it has been
  2372. // sent to. Also verify that the mail is plaintext.
  2373. $this->assertTrue(strpos($mail['body'], '*' . $mail['to'] . '*') !== FALSE);
  2374. $this->assertFalse(strpos($mail['body'], '<strong>'));
  2375. // Make sure the body is only attached once.
  2376. $this->assertEqual(1, preg_match_all('/Mail token/', $mail['body'], $matches));
  2377. }
  2378. // Report time. @todo: Find a way to actually do some assertions here.
  2379. $this->pass(t('Mails have been sent in @sec seconds with caching disabled.', array('@sec' => round($after - $before, 3))));
  2380. }
  2381. /**
  2382. * Test with disabled caching.
  2383. */
  2384. function testSendMissingNode() {
  2385. $this->setUpSubscribers(1);
  2386. $edit = array(
  2387. 'title' => $this->randomName(),
  2388. 'body[und][0][value]' => "Mail token: <strong>[simplenews-subscriber:mail]</strong>",
  2389. );
  2390. $this->drupalPost('node/add/simplenews', $edit, ('Save'));
  2391. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  2392. $node = node_load($matches[1]);
  2393. // Add node to spool.
  2394. simplenews_add_node_to_spool($node);
  2395. // Delete the node manually in the database.
  2396. db_delete('node')
  2397. ->condition('nid', $node->nid)
  2398. ->execute();
  2399. db_delete('node_revision')
  2400. ->condition('nid', $node->nid)
  2401. ->execute();
  2402. entity_get_controller('node')->resetCache();
  2403. simplenews_mail_spool();
  2404. // Make sure that no mails have been sent.
  2405. $this->assertEqual(0, count($this->drupalGetMails()));
  2406. $spool_row = db_query('SELECT * FROM {simplenews_mail_spool}')->fetchObject();
  2407. $this->assertEqual(SIMPLENEWS_SPOOL_DONE, $spool_row->status);
  2408. }
  2409. /**
  2410. * Test with disabled caching.
  2411. */
  2412. function testSendMissingSubscriber() {
  2413. $this->setUpSubscribers(1);
  2414. $edit = array(
  2415. 'title' => $this->randomName(),
  2416. 'body[und][0][value]' => "Mail token: <strong>[simplenews-subscriber:mail]</strong>",
  2417. );
  2418. $this->drupalPost('node/add/simplenews', $edit, ('Save'));
  2419. $this->assertTrue(preg_match('|node/(\d+)$|', $this->getUrl(), $matches), 'Node created');
  2420. $node = node_load($matches[1]);
  2421. // Add node to spool.
  2422. simplenews_add_node_to_spool($node);
  2423. // Delete the subscriber.
  2424. $subscriber = simplenews_subscriber_load_by_mail(reset($this->subscribers));
  2425. simplenews_subscriber_delete($subscriber);
  2426. simplenews_mail_spool();
  2427. // Make sure that no mails have been sent.
  2428. $this->assertEqual(0, count($this->drupalGetMails()));
  2429. $spool_row = db_query('SELECT * FROM {simplenews_mail_spool}')->fetchObject();
  2430. $this->assertEqual(SIMPLENEWS_SPOOL_DONE, $spool_row->status);
  2431. }
  2432. }
  2433. /**
  2434. * Unit tests for certain functions.
  2435. */
  2436. class SimplenewsUnitTest extends DrupalUnitTestCase {
  2437. function getInfo() {
  2438. return array(
  2439. 'name' => 'Unit tests',
  2440. 'description' => 'Unit tests for certain functions.',
  2441. 'group' => 'Simplenews',
  2442. );
  2443. }
  2444. public function testMasking() {
  2445. module_load_include('inc', 'simplenews', 'includes/simplenews.subscription');
  2446. $this->assertEqual('t*****@e*****.org', simplenews_mask_mail('test@example.org'));
  2447. $this->assertEqual('t*****@e*****.org', simplenews_mask_mail('t@example.org'));
  2448. $this->assertEqual('t*****@t*****.org', simplenews_mask_mail('t@test.example.org'));
  2449. $this->assertEqual('t*****@e*****', simplenews_mask_mail('t@example'));
  2450. }
  2451. }