Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

rcube_imap_generic.php 130KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2005-2015, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2012, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | Provide alternative IMAP library that doesn't rely on the standard |
  14. | C-Client based version. This allows to function regardless |
  15. | of whether or not the PHP build it's running on has IMAP |
  16. | functionality built-in. |
  17. | |
  18. | Based on Iloha IMAP Library. See http://ilohamail.org/ for details |
  19. +-----------------------------------------------------------------------+
  20. | Author: Aleksander Machniak <alec@alec.pl> |
  21. | Author: Ryo Chijiiwa <Ryo@IlohaMail.org> |
  22. +-----------------------------------------------------------------------+
  23. */
  24. /**
  25. * PHP based wrapper class to connect to an IMAP server
  26. *
  27. * @package Framework
  28. * @subpackage Storage
  29. */
  30. class rcube_imap_generic
  31. {
  32. public $error;
  33. public $errornum;
  34. public $result;
  35. public $resultcode;
  36. public $selected;
  37. public $data = array();
  38. public $flags = array(
  39. 'SEEN' => '\\Seen',
  40. 'DELETED' => '\\Deleted',
  41. 'ANSWERED' => '\\Answered',
  42. 'DRAFT' => '\\Draft',
  43. 'FLAGGED' => '\\Flagged',
  44. 'FORWARDED' => '$Forwarded',
  45. 'MDNSENT' => '$MDNSent',
  46. '*' => '\\*',
  47. );
  48. protected $fp;
  49. protected $host;
  50. protected $prefs;
  51. protected $cmd_tag;
  52. protected $cmd_num = 0;
  53. protected $resourceid;
  54. protected $logged = false;
  55. protected $capability = array();
  56. protected $capability_readed = false;
  57. protected $debug = false;
  58. protected $debug_handler = false;
  59. const ERROR_OK = 0;
  60. const ERROR_NO = -1;
  61. const ERROR_BAD = -2;
  62. const ERROR_BYE = -3;
  63. const ERROR_UNKNOWN = -4;
  64. const ERROR_COMMAND = -5;
  65. const ERROR_READONLY = -6;
  66. const COMMAND_NORESPONSE = 1;
  67. const COMMAND_CAPABILITY = 2;
  68. const COMMAND_LASTLINE = 4;
  69. const COMMAND_ANONYMIZED = 8;
  70. const DEBUG_LINE_LENGTH = 4098; // 4KB + 2B for \r\n
  71. /**
  72. * Send simple (one line) command to the connection stream
  73. *
  74. * @param string $string Command string
  75. * @param bool $endln True if CRLF need to be added at the end of command
  76. * @param bool $anonymized Don't write the given data to log but a placeholder
  77. *
  78. * @param int Number of bytes sent, False on error
  79. */
  80. protected function putLine($string, $endln = true, $anonymized = false)
  81. {
  82. if (!$this->fp) {
  83. return false;
  84. }
  85. if ($this->debug) {
  86. // anonymize the sent command for logging
  87. $cut = $endln ? 2 : 0;
  88. if ($anonymized && preg_match('/^(A\d+ (?:[A-Z]+ )+)(.+)/', $string, $m)) {
  89. $log = $m[1] . sprintf('****** [%d]', strlen($m[2]) - $cut);
  90. }
  91. else if ($anonymized) {
  92. $log = sprintf('****** [%d]', strlen($string) - $cut);
  93. }
  94. else {
  95. $log = rtrim($string);
  96. }
  97. $this->debug('C: ' . $log);
  98. }
  99. if ($endln) {
  100. $string .= "\r\n";
  101. }
  102. $res = fwrite($this->fp, $string);
  103. if ($res === false) {
  104. @fclose($this->fp);
  105. $this->fp = null;
  106. }
  107. return $res;
  108. }
  109. /**
  110. * Send command to the connection stream with Command Continuation
  111. * Requests (RFC3501 7.5) and LITERAL+ (RFC2088) support
  112. *
  113. * @param string $string Command string
  114. * @param bool $endln True if CRLF need to be added at the end of command
  115. * @param bool $anonymized Don't write the given data to log but a placeholder
  116. *
  117. * @return int|bool Number of bytes sent, False on error
  118. */
  119. protected function putLineC($string, $endln=true, $anonymized=false)
  120. {
  121. if (!$this->fp) {
  122. return false;
  123. }
  124. if ($endln) {
  125. $string .= "\r\n";
  126. }
  127. $res = 0;
  128. if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
  129. for ($i=0, $cnt=count($parts); $i<$cnt; $i++) {
  130. if (preg_match('/^\{([0-9]+)\}\r\n$/', $parts[$i+1], $matches)) {
  131. // LITERAL+ support
  132. if ($this->prefs['literal+']) {
  133. $parts[$i+1] = sprintf("{%d+}\r\n", $matches[1]);
  134. }
  135. $bytes = $this->putLine($parts[$i].$parts[$i+1], false, $anonymized);
  136. if ($bytes === false) {
  137. return false;
  138. }
  139. $res += $bytes;
  140. // don't wait if server supports LITERAL+ capability
  141. if (!$this->prefs['literal+']) {
  142. $line = $this->readLine(1000);
  143. // handle error in command
  144. if ($line[0] != '+') {
  145. return false;
  146. }
  147. }
  148. $i++;
  149. }
  150. else {
  151. $bytes = $this->putLine($parts[$i], false, $anonymized);
  152. if ($bytes === false) {
  153. return false;
  154. }
  155. $res += $bytes;
  156. }
  157. }
  158. }
  159. return $res;
  160. }
  161. /**
  162. * Reads line from the connection stream
  163. *
  164. * @param int $size Buffer size
  165. *
  166. * @return string Line of text response
  167. */
  168. protected function readLine($size = 1024)
  169. {
  170. $line = '';
  171. if (!$size) {
  172. $size = 1024;
  173. }
  174. do {
  175. if ($this->eof()) {
  176. return $line ?: null;
  177. }
  178. $buffer = fgets($this->fp, $size);
  179. if ($buffer === false) {
  180. $this->closeSocket();
  181. break;
  182. }
  183. if ($this->debug) {
  184. $this->debug('S: '. rtrim($buffer));
  185. }
  186. $line .= $buffer;
  187. }
  188. while (substr($buffer, -1) != "\n");
  189. return $line;
  190. }
  191. /**
  192. * Reads more data from the connection stream when provided
  193. * data contain string literal
  194. *
  195. * @param string $line Response text
  196. * @param bool $escape Enables escaping
  197. *
  198. * @return string Line of text response
  199. */
  200. protected function multLine($line, $escape = false)
  201. {
  202. $line = rtrim($line);
  203. if (preg_match('/\{([0-9]+)\}$/', $line, $m)) {
  204. $out = '';
  205. $str = substr($line, 0, -strlen($m[0]));
  206. $bytes = $m[1];
  207. while (strlen($out) < $bytes) {
  208. $line = $this->readBytes($bytes);
  209. if ($line === null) {
  210. break;
  211. }
  212. $out .= $line;
  213. }
  214. $line = $str . ($escape ? $this->escape($out) : $out);
  215. }
  216. return $line;
  217. }
  218. /**
  219. * Reads specified number of bytes from the connection stream
  220. *
  221. * @param int $bytes Number of bytes to get
  222. *
  223. * @return string Response text
  224. */
  225. protected function readBytes($bytes)
  226. {
  227. $data = '';
  228. $len = 0;
  229. while ($len < $bytes && !$this->eof()) {
  230. $d = fread($this->fp, $bytes-$len);
  231. if ($this->debug) {
  232. $this->debug('S: '. $d);
  233. }
  234. $data .= $d;
  235. $data_len = strlen($data);
  236. if ($len == $data_len) {
  237. break; // nothing was read -> exit to avoid apache lockups
  238. }
  239. $len = $data_len;
  240. }
  241. return $data;
  242. }
  243. /**
  244. * Reads complete response to the IMAP command
  245. *
  246. * @param array $untagged Will be filled with untagged response lines
  247. *
  248. * @return string Response text
  249. */
  250. protected function readReply(&$untagged = null)
  251. {
  252. do {
  253. $line = trim($this->readLine(1024));
  254. // store untagged response lines
  255. if ($line[0] == '*') {
  256. $untagged[] = $line;
  257. }
  258. }
  259. while ($line[0] == '*');
  260. if ($untagged) {
  261. $untagged = join("\n", $untagged);
  262. }
  263. return $line;
  264. }
  265. /**
  266. * Response parser.
  267. *
  268. * @param string $string Response text
  269. * @param string $err_prefix Error message prefix
  270. *
  271. * @return int Response status
  272. */
  273. protected function parseResult($string, $err_prefix = '')
  274. {
  275. if (preg_match('/^[a-z0-9*]+ (OK|NO|BAD|BYE)(.*)$/i', trim($string), $matches)) {
  276. $res = strtoupper($matches[1]);
  277. $str = trim($matches[2]);
  278. if ($res == 'OK') {
  279. $this->errornum = self::ERROR_OK;
  280. }
  281. else if ($res == 'NO') {
  282. $this->errornum = self::ERROR_NO;
  283. }
  284. else if ($res == 'BAD') {
  285. $this->errornum = self::ERROR_BAD;
  286. }
  287. else if ($res == 'BYE') {
  288. $this->closeSocket();
  289. $this->errornum = self::ERROR_BYE;
  290. }
  291. if ($str) {
  292. $str = trim($str);
  293. // get response string and code (RFC5530)
  294. if (preg_match("/^\[([a-z-]+)\]/i", $str, $m)) {
  295. $this->resultcode = strtoupper($m[1]);
  296. $str = trim(substr($str, strlen($m[1]) + 2));
  297. }
  298. else {
  299. $this->resultcode = null;
  300. // parse response for [APPENDUID 1204196876 3456]
  301. if (preg_match("/^\[APPENDUID [0-9]+ ([0-9]+)\]/i", $str, $m)) {
  302. $this->data['APPENDUID'] = $m[1];
  303. }
  304. // parse response for [COPYUID 1204196876 3456:3457 123:124]
  305. else if (preg_match("/^\[COPYUID [0-9]+ ([0-9,:]+) ([0-9,:]+)\]/i", $str, $m)) {
  306. $this->data['COPYUID'] = array($m[1], $m[2]);
  307. }
  308. }
  309. $this->result = $str;
  310. if ($this->errornum != self::ERROR_OK) {
  311. $this->error = $err_prefix ? $err_prefix.$str : $str;
  312. }
  313. }
  314. return $this->errornum;
  315. }
  316. return self::ERROR_UNKNOWN;
  317. }
  318. /**
  319. * Checks connection stream state.
  320. *
  321. * @return bool True if connection is closed
  322. */
  323. protected function eof()
  324. {
  325. if (!is_resource($this->fp)) {
  326. return true;
  327. }
  328. // If a connection opened by fsockopen() wasn't closed
  329. // by the server, feof() will hang.
  330. $start = microtime(true);
  331. if (feof($this->fp) ||
  332. ($this->prefs['timeout'] && (microtime(true) - $start > $this->prefs['timeout']))
  333. ) {
  334. $this->closeSocket();
  335. return true;
  336. }
  337. return false;
  338. }
  339. /**
  340. * Closes connection stream.
  341. */
  342. protected function closeSocket()
  343. {
  344. @fclose($this->fp);
  345. $this->fp = null;
  346. }
  347. /**
  348. * Error code/message setter.
  349. */
  350. protected function setError($code, $msg = '')
  351. {
  352. $this->errornum = $code;
  353. $this->error = $msg;
  354. }
  355. /**
  356. * Checks response status.
  357. * Checks if command response line starts with specified prefix (or * BYE/BAD)
  358. *
  359. * @param string $string Response text
  360. * @param string $match Prefix to match with (case-sensitive)
  361. * @param bool $error Enables BYE/BAD checking
  362. * @param bool $nonempty Enables empty response checking
  363. *
  364. * @return bool True any check is true or connection is closed.
  365. */
  366. protected function startsWith($string, $match, $error = false, $nonempty = false)
  367. {
  368. if (!$this->fp) {
  369. return true;
  370. }
  371. if (strncmp($string, $match, strlen($match)) == 0) {
  372. return true;
  373. }
  374. if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
  375. if (strtoupper($m[1]) == 'BYE') {
  376. $this->closeSocket();
  377. }
  378. return true;
  379. }
  380. if ($nonempty && !strlen($string)) {
  381. return true;
  382. }
  383. return false;
  384. }
  385. /**
  386. * Capabilities checker
  387. */
  388. protected function hasCapability($name)
  389. {
  390. if (empty($this->capability) || $name == '') {
  391. return false;
  392. }
  393. if (in_array($name, $this->capability)) {
  394. return true;
  395. }
  396. else if (strpos($name, '=')) {
  397. return false;
  398. }
  399. $result = array();
  400. foreach ($this->capability as $cap) {
  401. $entry = explode('=', $cap);
  402. if ($entry[0] == $name) {
  403. $result[] = $entry[1];
  404. }
  405. }
  406. return $result ?: false;
  407. }
  408. /**
  409. * Capabilities checker
  410. *
  411. * @param string $name Capability name
  412. *
  413. * @return mixed Capability values array for key=value pairs, true/false for others
  414. */
  415. public function getCapability($name)
  416. {
  417. $result = $this->hasCapability($name);
  418. if (!empty($result)) {
  419. return $result;
  420. }
  421. else if ($this->capability_readed) {
  422. return false;
  423. }
  424. // get capabilities (only once) because initial
  425. // optional CAPABILITY response may differ
  426. $result = $this->execute('CAPABILITY');
  427. if ($result[0] == self::ERROR_OK) {
  428. $this->parseCapability($result[1]);
  429. }
  430. $this->capability_readed = true;
  431. return $this->hasCapability($name);
  432. }
  433. /**
  434. * Clears detected server capabilities
  435. */
  436. public function clearCapability()
  437. {
  438. $this->capability = array();
  439. $this->capability_readed = false;
  440. }
  441. /**
  442. * DIGEST-MD5/CRAM-MD5/PLAIN Authentication
  443. *
  444. * @param string $user Username
  445. * @param string $pass Password
  446. * @param string $type Authentication type (PLAIN/CRAM-MD5/DIGEST-MD5)
  447. *
  448. * @return resource Connection resourse on success, error code on error
  449. */
  450. protected function authenticate($user, $pass, $type = 'PLAIN')
  451. {
  452. if ($type == 'CRAM-MD5' || $type == 'DIGEST-MD5') {
  453. if ($type == 'DIGEST-MD5' && !class_exists('Auth_SASL')) {
  454. $this->setError(self::ERROR_BYE,
  455. "The Auth_SASL package is required for DIGEST-MD5 authentication");
  456. return self::ERROR_BAD;
  457. }
  458. $this->putLine($this->nextTag() . " AUTHENTICATE $type");
  459. $line = trim($this->readReply());
  460. if ($line[0] == '+') {
  461. $challenge = substr($line, 2);
  462. }
  463. else {
  464. return $this->parseResult($line);
  465. }
  466. if ($type == 'CRAM-MD5') {
  467. // RFC2195: CRAM-MD5
  468. $ipad = '';
  469. $opad = '';
  470. // initialize ipad, opad
  471. for ($i=0; $i<64; $i++) {
  472. $ipad .= chr(0x36);
  473. $opad .= chr(0x5C);
  474. }
  475. // pad $pass so it's 64 bytes
  476. $padLen = 64 - strlen($pass);
  477. for ($i=0; $i<$padLen; $i++) {
  478. $pass .= chr(0);
  479. }
  480. // generate hash
  481. $hash = md5($this->_xor($pass, $opad) . pack("H*",
  482. md5($this->_xor($pass, $ipad) . base64_decode($challenge))));
  483. $reply = base64_encode($user . ' ' . $hash);
  484. // send result
  485. $this->putLine($reply, true, true);
  486. }
  487. else {
  488. // RFC2831: DIGEST-MD5
  489. // proxy authorization
  490. if (!empty($this->prefs['auth_cid'])) {
  491. $authc = $this->prefs['auth_cid'];
  492. $pass = $this->prefs['auth_pw'];
  493. }
  494. else {
  495. $authc = $user;
  496. $user = '';
  497. }
  498. $auth_sasl = new Auth_SASL;
  499. $auth_sasl = $auth_sasl->factory('digestmd5');
  500. $reply = base64_encode($auth_sasl->getResponse($authc, $pass,
  501. base64_decode($challenge), $this->host, 'imap', $user));
  502. // send result
  503. $this->putLine($reply, true, true);
  504. $line = trim($this->readReply());
  505. if ($line[0] != '+') {
  506. return $this->parseResult($line);
  507. }
  508. // check response
  509. $challenge = substr($line, 2);
  510. $challenge = base64_decode($challenge);
  511. if (strpos($challenge, 'rspauth=') === false) {
  512. $this->setError(self::ERROR_BAD,
  513. "Unexpected response from server to DIGEST-MD5 response");
  514. return self::ERROR_BAD;
  515. }
  516. $this->putLine('');
  517. }
  518. $line = $this->readReply();
  519. $result = $this->parseResult($line);
  520. }
  521. else if ($type == 'GSSAPI') {
  522. if (!extension_loaded('krb5')) {
  523. $this->setError(self::ERROR_BYE,
  524. "The krb5 extension is required for GSSAPI authentication");
  525. return self::ERROR_BAD;
  526. }
  527. if (empty($this->prefs['gssapi_cn'])) {
  528. $this->setError(self::ERROR_BYE,
  529. "The gssapi_cn parameter is required for GSSAPI authentication");
  530. return self::ERROR_BAD;
  531. }
  532. if (empty($this->prefs['gssapi_context'])) {
  533. $this->setError(self::ERROR_BYE,
  534. "The gssapi_context parameter is required for GSSAPI authentication");
  535. return self::ERROR_BAD;
  536. }
  537. putenv('KRB5CCNAME=' . $this->prefs['gssapi_cn']);
  538. try {
  539. $ccache = new KRB5CCache();
  540. $ccache->open($this->prefs['gssapi_cn']);
  541. $gssapicontext = new GSSAPIContext();
  542. $gssapicontext->acquireCredentials($ccache);
  543. $token = '';
  544. $success = $gssapicontext->initSecContext($this->prefs['gssapi_context'], null, null, null, $token);
  545. $token = base64_encode($token);
  546. }
  547. catch (Exception $e) {
  548. trigger_error($e->getMessage(), E_USER_WARNING);
  549. $this->setError(self::ERROR_BYE, "GSSAPI authentication failed");
  550. return self::ERROR_BAD;
  551. }
  552. $this->putLine($this->nextTag() . " AUTHENTICATE GSSAPI " . $token);
  553. $line = trim($this->readReply());
  554. if ($line[0] != '+') {
  555. return $this->parseResult($line);
  556. }
  557. try {
  558. $challenge = base64_decode(substr($line, 2));
  559. $gssapicontext->unwrap($challenge, $challenge);
  560. $gssapicontext->wrap($challenge, $challenge, true);
  561. }
  562. catch (Exception $e) {
  563. trigger_error($e->getMessage(), E_USER_WARNING);
  564. $this->setError(self::ERROR_BYE, "GSSAPI authentication failed");
  565. return self::ERROR_BAD;
  566. }
  567. $this->putLine(base64_encode($challenge));
  568. $line = $this->readReply();
  569. $result = $this->parseResult($line);
  570. }
  571. else { // PLAIN
  572. // proxy authorization
  573. if (!empty($this->prefs['auth_cid'])) {
  574. $authc = $this->prefs['auth_cid'];
  575. $pass = $this->prefs['auth_pw'];
  576. }
  577. else {
  578. $authc = $user;
  579. $user = '';
  580. }
  581. $reply = base64_encode($user . chr(0) . $authc . chr(0) . $pass);
  582. // RFC 4959 (SASL-IR): save one round trip
  583. if ($this->getCapability('SASL-IR')) {
  584. list($result, $line) = $this->execute("AUTHENTICATE PLAIN", array($reply),
  585. self::COMMAND_LASTLINE | self::COMMAND_CAPABILITY | self::COMMAND_ANONYMIZED);
  586. }
  587. else {
  588. $this->putLine($this->nextTag() . " AUTHENTICATE PLAIN");
  589. $line = trim($this->readReply());
  590. if ($line[0] != '+') {
  591. return $this->parseResult($line);
  592. }
  593. // send result, get reply and process it
  594. $this->putLine($reply, true, true);
  595. $line = $this->readReply();
  596. $result = $this->parseResult($line);
  597. }
  598. }
  599. if ($result == self::ERROR_OK) {
  600. // optional CAPABILITY response
  601. if ($line && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
  602. $this->parseCapability($matches[1], true);
  603. }
  604. return $this->fp;
  605. }
  606. else {
  607. $this->setError($result, "AUTHENTICATE $type: $line");
  608. }
  609. return $result;
  610. }
  611. /**
  612. * LOGIN Authentication
  613. *
  614. * @param string $user Username
  615. * @param string $pass Password
  616. *
  617. * @return resource Connection resourse on success, error code on error
  618. */
  619. protected function login($user, $password)
  620. {
  621. list($code, $response) = $this->execute('LOGIN', array(
  622. $this->escape($user), $this->escape($password)), self::COMMAND_CAPABILITY | self::COMMAND_ANONYMIZED);
  623. // re-set capabilities list if untagged CAPABILITY response provided
  624. if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
  625. $this->parseCapability($matches[1], true);
  626. }
  627. if ($code == self::ERROR_OK) {
  628. return $this->fp;
  629. }
  630. return $code;
  631. }
  632. /**
  633. * Detects hierarchy delimiter
  634. *
  635. * @return string The delimiter
  636. */
  637. public function getHierarchyDelimiter()
  638. {
  639. if ($this->prefs['delimiter']) {
  640. return $this->prefs['delimiter'];
  641. }
  642. // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
  643. list($code, $response) = $this->execute('LIST',
  644. array($this->escape(''), $this->escape('')));
  645. if ($code == self::ERROR_OK) {
  646. $args = $this->tokenizeResponse($response, 4);
  647. $delimiter = $args[3];
  648. if (strlen($delimiter) > 0) {
  649. return ($this->prefs['delimiter'] = $delimiter);
  650. }
  651. }
  652. }
  653. /**
  654. * NAMESPACE handler (RFC 2342)
  655. *
  656. * @return array Namespace data hash (personal, other, shared)
  657. */
  658. public function getNamespace()
  659. {
  660. if (array_key_exists('namespace', $this->prefs)) {
  661. return $this->prefs['namespace'];
  662. }
  663. if (!$this->getCapability('NAMESPACE')) {
  664. return self::ERROR_BAD;
  665. }
  666. list($code, $response) = $this->execute('NAMESPACE');
  667. if ($code == self::ERROR_OK && preg_match('/^\* NAMESPACE /', $response)) {
  668. $response = substr($response, 11);
  669. $data = $this->tokenizeResponse($response);
  670. }
  671. if (!is_array($data)) {
  672. return $code;
  673. }
  674. $this->prefs['namespace'] = array(
  675. 'personal' => $data[0],
  676. 'other' => $data[1],
  677. 'shared' => $data[2],
  678. );
  679. return $this->prefs['namespace'];
  680. }
  681. /**
  682. * Connects to IMAP server and authenticates.
  683. *
  684. * @param string $host Server hostname or IP
  685. * @param string $user User name
  686. * @param string $password Password
  687. * @param array $options Connection and class options
  688. *
  689. * @return bool True on success, False on failure
  690. */
  691. public function connect($host, $user, $password, $options = null)
  692. {
  693. // configure
  694. $this->set_prefs($options);
  695. $this->host = $host;
  696. $this->user = $user;
  697. $this->logged = false;
  698. $this->selected = null;
  699. // check input
  700. if (empty($host)) {
  701. $this->setError(self::ERROR_BAD, "Empty host");
  702. return false;
  703. }
  704. if (empty($user)) {
  705. $this->setError(self::ERROR_NO, "Empty user");
  706. return false;
  707. }
  708. if (empty($password) && empty($options['gssapi_cn'])) {
  709. $this->setError(self::ERROR_NO, "Empty password");
  710. return false;
  711. }
  712. // Connect
  713. if (!$this->_connect($host)) {
  714. return false;
  715. }
  716. // Send ID info
  717. if (!empty($this->prefs['ident']) && $this->getCapability('ID')) {
  718. $this->data['ID'] = $this->id($this->prefs['ident']);
  719. }
  720. $auth_method = $this->prefs['auth_type'];
  721. $auth_methods = array();
  722. $result = null;
  723. // check for supported auth methods
  724. if ($auth_method == 'CHECK') {
  725. if ($auth_caps = $this->getCapability('AUTH')) {
  726. $auth_methods = $auth_caps;
  727. }
  728. // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
  729. $login_disabled = $this->getCapability('LOGINDISABLED');
  730. if (($key = array_search('LOGIN', $auth_methods)) !== false) {
  731. if ($login_disabled) {
  732. unset($auth_methods[$key]);
  733. }
  734. }
  735. else if (!$login_disabled) {
  736. $auth_methods[] = 'LOGIN';
  737. }
  738. // Use best (for security) supported authentication method
  739. $all_methods = array('GSSAPI', 'DIGEST-MD5', 'CRAM-MD5', 'CRAM_MD5', 'PLAIN', 'LOGIN');
  740. foreach ($all_methods as $auth_method) {
  741. if (in_array($auth_method, $auth_methods)) {
  742. break;
  743. }
  744. }
  745. }
  746. else {
  747. // Prevent from sending credentials in plain text when connection is not secure
  748. if ($auth_method == 'LOGIN' && $this->getCapability('LOGINDISABLED')) {
  749. $this->setError(self::ERROR_BAD, "Login disabled by IMAP server");
  750. $this->closeConnection();
  751. return false;
  752. }
  753. // replace AUTH with CRAM-MD5 for backward compat.
  754. if ($auth_method == 'AUTH') {
  755. $auth_method = 'CRAM-MD5';
  756. }
  757. }
  758. // pre-login capabilities can be not complete
  759. $this->capability_readed = false;
  760. // Authenticate
  761. switch ($auth_method) {
  762. case 'CRAM_MD5':
  763. $auth_method = 'CRAM-MD5';
  764. case 'CRAM-MD5':
  765. case 'DIGEST-MD5':
  766. case 'PLAIN':
  767. case 'GSSAPI':
  768. $result = $this->authenticate($user, $password, $auth_method);
  769. break;
  770. case 'LOGIN':
  771. $result = $this->login($user, $password);
  772. break;
  773. default:
  774. $this->setError(self::ERROR_BAD, "Configuration error. Unknown auth method: $auth_method");
  775. }
  776. // Connected and authenticated
  777. if (is_resource($result)) {
  778. if ($this->prefs['force_caps']) {
  779. $this->clearCapability();
  780. }
  781. $this->logged = true;
  782. return true;
  783. }
  784. $this->closeConnection();
  785. return false;
  786. }
  787. /**
  788. * Connects to IMAP server.
  789. *
  790. * @param string $host Server hostname or IP
  791. *
  792. * @return bool True on success, False on failure
  793. */
  794. protected function _connect($host)
  795. {
  796. // initialize connection
  797. $this->error = '';
  798. $this->errornum = self::ERROR_OK;
  799. if (!$this->prefs['port']) {
  800. $this->prefs['port'] = 143;
  801. }
  802. // check for SSL
  803. if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
  804. $host = $this->prefs['ssl_mode'] . '://' . $host;
  805. }
  806. if ($this->prefs['timeout'] <= 0) {
  807. $this->prefs['timeout'] = max(0, intval(ini_get('default_socket_timeout')));
  808. }
  809. if (!empty($this->prefs['socket_options'])) {
  810. $context = stream_context_create($this->prefs['socket_options']);
  811. $this->fp = stream_socket_client($host . ':' . $this->prefs['port'], $errno, $errstr,
  812. $this->prefs['timeout'], STREAM_CLIENT_CONNECT, $context);
  813. }
  814. else {
  815. $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
  816. }
  817. if (!$this->fp) {
  818. $this->setError(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s",
  819. $host, $this->prefs['port'], $errstr ?: "Unknown reason"));
  820. return false;
  821. }
  822. if ($this->prefs['timeout'] > 0) {
  823. stream_set_timeout($this->fp, $this->prefs['timeout']);
  824. }
  825. $line = trim(fgets($this->fp, 8192));
  826. if ($this->debug) {
  827. // set connection identifier for debug output
  828. preg_match('/#([0-9]+)/', (string) $this->fp, $m);
  829. $this->resourceid = strtoupper(substr(md5($m[1].$this->user.microtime()), 0, 4));
  830. if ($line) {
  831. $this->debug('S: '. $line);
  832. }
  833. }
  834. // Connected to wrong port or connection error?
  835. if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
  836. if ($line)
  837. $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
  838. else
  839. $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
  840. $this->setError(self::ERROR_BAD, $error);
  841. $this->closeConnection();
  842. return false;
  843. }
  844. $this->data['GREETING'] = trim(preg_replace('/\[[^\]]+\]\s*/', '', $line));
  845. // RFC3501 [7.1] optional CAPABILITY response
  846. if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
  847. $this->parseCapability($matches[1], true);
  848. }
  849. // TLS connection
  850. if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
  851. $res = $this->execute('STARTTLS');
  852. if ($res[0] != self::ERROR_OK) {
  853. $this->closeConnection();
  854. return false;
  855. }
  856. if (isset($this->prefs['socket_options']['ssl']['crypto_method'])) {
  857. $crypto_method = $this->prefs['socket_options']['ssl']['crypto_method'];
  858. }
  859. else {
  860. // There is no flag to enable all TLS methods. Net_SMTP
  861. // handles enabling TLS similarly.
  862. $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT
  863. | @STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  864. | @STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
  865. }
  866. if (!stream_socket_enable_crypto($this->fp, true, $crypto_method)) {
  867. $this->setError(self::ERROR_BAD, "Unable to negotiate TLS");
  868. $this->closeConnection();
  869. return false;
  870. }
  871. // Now we're secure, capabilities need to be reread
  872. $this->clearCapability();
  873. }
  874. return true;
  875. }
  876. /**
  877. * Initializes environment
  878. */
  879. protected function set_prefs($prefs)
  880. {
  881. // set preferences
  882. if (is_array($prefs)) {
  883. $this->prefs = $prefs;
  884. }
  885. // set auth method
  886. if (!empty($this->prefs['auth_type'])) {
  887. $this->prefs['auth_type'] = strtoupper($this->prefs['auth_type']);
  888. }
  889. else {
  890. $this->prefs['auth_type'] = 'CHECK';
  891. }
  892. // disabled capabilities
  893. if (!empty($this->prefs['disabled_caps'])) {
  894. $this->prefs['disabled_caps'] = array_map('strtoupper', (array)$this->prefs['disabled_caps']);
  895. }
  896. // additional message flags
  897. if (!empty($this->prefs['message_flags'])) {
  898. $this->flags = array_merge($this->flags, $this->prefs['message_flags']);
  899. unset($this->prefs['message_flags']);
  900. }
  901. }
  902. /**
  903. * Checks connection status
  904. *
  905. * @return bool True if connection is active and user is logged in, False otherwise.
  906. */
  907. public function connected()
  908. {
  909. return $this->fp && $this->logged;
  910. }
  911. /**
  912. * Closes connection with logout.
  913. */
  914. public function closeConnection()
  915. {
  916. if ($this->logged && $this->putLine($this->nextTag() . ' LOGOUT')) {
  917. $this->readReply();
  918. }
  919. $this->closeSocket();
  920. }
  921. /**
  922. * Executes SELECT command (if mailbox is already not in selected state)
  923. *
  924. * @param string $mailbox Mailbox name
  925. * @param array $qresync_data QRESYNC data (RFC5162)
  926. *
  927. * @return boolean True on success, false on error
  928. */
  929. public function select($mailbox, $qresync_data = null)
  930. {
  931. if (!strlen($mailbox)) {
  932. return false;
  933. }
  934. if ($this->selected === $mailbox) {
  935. return true;
  936. }
  937. /*
  938. Temporary commented out because Courier returns \Noselect for INBOX
  939. Requires more investigation
  940. if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
  941. if (in_array('\\Noselect', $opts)) {
  942. return false;
  943. }
  944. }
  945. */
  946. $params = array($this->escape($mailbox));
  947. // QRESYNC data items
  948. // 0. the last known UIDVALIDITY,
  949. // 1. the last known modification sequence,
  950. // 2. the optional set of known UIDs, and
  951. // 3. an optional parenthesized list of known sequence ranges and their
  952. // corresponding UIDs.
  953. if (!empty($qresync_data)) {
  954. if (!empty($qresync_data[2])) {
  955. $qresync_data[2] = self::compressMessageSet($qresync_data[2]);
  956. }
  957. $params[] = array('QRESYNC', $qresync_data);
  958. }
  959. list($code, $response) = $this->execute('SELECT', $params);
  960. if ($code == self::ERROR_OK) {
  961. $this->clear_mailbox_cache();
  962. $response = explode("\r\n", $response);
  963. foreach ($response as $line) {
  964. if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/i', $line, $m)) {
  965. $this->data[strtoupper($m[2])] = (int) $m[1];
  966. }
  967. else if (preg_match('/^\* OK \[/i', $line, $match)) {
  968. $line = substr($line, 6);
  969. if (preg_match('/^(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)/i', $line, $match)) {
  970. $this->data[strtoupper($match[1])] = (int) $match[2];
  971. }
  972. else if (preg_match('/^(HIGHESTMODSEQ) ([0-9]+)/i', $line, $match)) {
  973. $this->data[strtoupper($match[1])] = (string) $match[2];
  974. }
  975. else if (preg_match('/^(NOMODSEQ)/i', $line, $match)) {
  976. $this->data[strtoupper($match[1])] = true;
  977. }
  978. else if (preg_match('/^PERMANENTFLAGS \(([^\)]+)\)/iU', $line, $match)) {
  979. $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
  980. }
  981. }
  982. // QRESYNC FETCH response (RFC5162)
  983. else if (preg_match('/^\* ([0-9+]) FETCH/i', $line, $match)) {
  984. $line = substr($line, strlen($match[0]));
  985. $fetch_data = $this->tokenizeResponse($line, 1);
  986. $data = array('id' => $match[1]);
  987. for ($i=0, $size=count($fetch_data); $i<$size; $i+=2) {
  988. $data[strtolower($fetch_data[$i])] = $fetch_data[$i+1];
  989. }
  990. $this->data['QRESYNC'][$data['uid']] = $data;
  991. }
  992. // QRESYNC VANISHED response (RFC5162)
  993. else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
  994. $line = substr($line, strlen($match[0]));
  995. $v_data = $this->tokenizeResponse($line, 1);
  996. $this->data['VANISHED'] = $v_data;
  997. }
  998. }
  999. $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
  1000. $this->selected = $mailbox;
  1001. return true;
  1002. }
  1003. return false;
  1004. }
  1005. /**
  1006. * Executes STATUS command
  1007. *
  1008. * @param string $mailbox Mailbox name
  1009. * @param array $items Additional requested item names. By default
  1010. * MESSAGES and UNSEEN are requested. Other defined
  1011. * in RFC3501: UIDNEXT, UIDVALIDITY, RECENT
  1012. *
  1013. * @return array Status item-value hash
  1014. * @since 0.5-beta
  1015. */
  1016. public function status($mailbox, $items = array())
  1017. {
  1018. if (!strlen($mailbox)) {
  1019. return false;
  1020. }
  1021. if (!in_array('MESSAGES', $items)) {
  1022. $items[] = 'MESSAGES';
  1023. }
  1024. if (!in_array('UNSEEN', $items)) {
  1025. $items[] = 'UNSEEN';
  1026. }
  1027. list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
  1028. '(' . implode(' ', (array) $items) . ')'));
  1029. if ($code == self::ERROR_OK && preg_match('/^\* STATUS /i', $response)) {
  1030. $result = array();
  1031. $response = substr($response, 9); // remove prefix "* STATUS "
  1032. list($mbox, $items) = $this->tokenizeResponse($response, 2);
  1033. // Fix for #1487859. Some buggy server returns not quoted
  1034. // folder name with spaces. Let's try to handle this situation
  1035. if (!is_array($items) && ($pos = strpos($response, '(')) !== false) {
  1036. $response = substr($response, $pos);
  1037. $items = $this->tokenizeResponse($response, 1);
  1038. if (!is_array($items)) {
  1039. return $result;
  1040. }
  1041. }
  1042. for ($i=0, $len=count($items); $i<$len; $i += 2) {
  1043. $result[$items[$i]] = $items[$i+1];
  1044. }
  1045. $this->data['STATUS:'.$mailbox] = $result;
  1046. return $result;
  1047. }
  1048. return false;
  1049. }
  1050. /**
  1051. * Executes EXPUNGE command
  1052. *
  1053. * @param string $mailbox Mailbox name
  1054. * @param string|array $messages Message UIDs to expunge
  1055. *
  1056. * @return boolean True on success, False on error
  1057. */
  1058. public function expunge($mailbox, $messages = null)
  1059. {
  1060. if (!$this->select($mailbox)) {
  1061. return false;
  1062. }
  1063. if (!$this->data['READ-WRITE']) {
  1064. $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
  1065. return false;
  1066. }
  1067. // Clear internal status cache
  1068. $this->clear_status_cache($mailbox);
  1069. if (!empty($messages) && $messages != '*' && $this->hasCapability('UIDPLUS')) {
  1070. $messages = self::compressMessageSet($messages);
  1071. $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
  1072. }
  1073. else {
  1074. $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
  1075. }
  1076. if ($result == self::ERROR_OK) {
  1077. $this->selected = null; // state has changed, need to reselect
  1078. return true;
  1079. }
  1080. return false;
  1081. }
  1082. /**
  1083. * Executes CLOSE command
  1084. *
  1085. * @return boolean True on success, False on error
  1086. * @since 0.5
  1087. */
  1088. public function close()
  1089. {
  1090. $result = $this->execute('CLOSE', null, self::COMMAND_NORESPONSE);
  1091. if ($result == self::ERROR_OK) {
  1092. $this->selected = null;
  1093. return true;
  1094. }
  1095. return false;
  1096. }
  1097. /**
  1098. * Folder subscription (SUBSCRIBE)
  1099. *
  1100. * @param string $mailbox Mailbox name
  1101. *
  1102. * @return boolean True on success, False on error
  1103. */
  1104. public function subscribe($mailbox)
  1105. {
  1106. $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
  1107. self::COMMAND_NORESPONSE);
  1108. return $result == self::ERROR_OK;
  1109. }
  1110. /**
  1111. * Folder unsubscription (UNSUBSCRIBE)
  1112. *
  1113. * @param string $mailbox Mailbox name
  1114. *
  1115. * @return boolean True on success, False on error
  1116. */
  1117. public function unsubscribe($mailbox)
  1118. {
  1119. $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
  1120. self::COMMAND_NORESPONSE);
  1121. return $result == self::ERROR_OK;
  1122. }
  1123. /**
  1124. * Folder creation (CREATE)
  1125. *
  1126. * @param string $mailbox Mailbox name
  1127. * @param array $types Optional folder types (RFC 6154)
  1128. *
  1129. * @return bool True on success, False on error
  1130. */
  1131. public function createFolder($mailbox, $types = null)
  1132. {
  1133. $args = array($this->escape($mailbox));
  1134. // RFC 6154: CREATE-SPECIAL-USE
  1135. if (!empty($types) && $this->getCapability('CREATE-SPECIAL-USE')) {
  1136. $args[] = '(USE (' . implode(' ', $types) . '))';
  1137. }
  1138. $result = $this->execute('CREATE', $args, self::COMMAND_NORESPONSE);
  1139. return $result == self::ERROR_OK;
  1140. }
  1141. /**
  1142. * Folder renaming (RENAME)
  1143. *
  1144. * @param string $mailbox Mailbox name
  1145. *
  1146. * @return bool True on success, False on error
  1147. */
  1148. public function renameFolder($from, $to)
  1149. {
  1150. $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
  1151. self::COMMAND_NORESPONSE);
  1152. return $result == self::ERROR_OK;
  1153. }
  1154. /**
  1155. * Executes DELETE command
  1156. *
  1157. * @param string $mailbox Mailbox name
  1158. *
  1159. * @return boolean True on success, False on error
  1160. */
  1161. public function deleteFolder($mailbox)
  1162. {
  1163. $result = $this->execute('DELETE', array($this->escape($mailbox)),
  1164. self::COMMAND_NORESPONSE);
  1165. return $result == self::ERROR_OK;
  1166. }
  1167. /**
  1168. * Removes all messages in a folder
  1169. *
  1170. * @param string $mailbox Mailbox name
  1171. *
  1172. * @return boolean True on success, False on error
  1173. */
  1174. public function clearFolder($mailbox)
  1175. {
  1176. if ($this->countMessages($mailbox) > 0) {
  1177. $res = $this->flag($mailbox, '1:*', 'DELETED');
  1178. }
  1179. if ($res) {
  1180. if ($this->selected === $mailbox) {
  1181. $res = $this->close();
  1182. }
  1183. else {
  1184. $res = $this->expunge($mailbox);
  1185. }
  1186. }
  1187. return $res;
  1188. }
  1189. /**
  1190. * Returns list of mailboxes
  1191. *
  1192. * @param string $ref Reference name
  1193. * @param string $mailbox Mailbox name
  1194. * @param array $return_opts (see self::_listMailboxes)
  1195. * @param array $select_opts (see self::_listMailboxes)
  1196. *
  1197. * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
  1198. * is requested, False on error.
  1199. */
  1200. public function listMailboxes($ref, $mailbox, $return_opts = array(), $select_opts = array())
  1201. {
  1202. return $this->_listMailboxes($ref, $mailbox, false, $return_opts, $select_opts);
  1203. }
  1204. /**
  1205. * Returns list of subscribed mailboxes
  1206. *
  1207. * @param string $ref Reference name
  1208. * @param string $mailbox Mailbox name
  1209. * @param array $return_opts (see self::_listMailboxes)
  1210. *
  1211. * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
  1212. * is requested, False on error.
  1213. */
  1214. public function listSubscribed($ref, $mailbox, $return_opts = array())
  1215. {
  1216. return $this->_listMailboxes($ref, $mailbox, true, $return_opts, null);
  1217. }
  1218. /**
  1219. * IMAP LIST/LSUB command
  1220. *
  1221. * @param string $ref Reference name
  1222. * @param string $mailbox Mailbox name
  1223. * @param bool $subscribed Enables returning subscribed mailboxes only
  1224. * @param array $return_opts List of RETURN options (RFC5819: LIST-STATUS, RFC5258: LIST-EXTENDED)
  1225. * Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN,
  1226. * MYRIGHTS, SUBSCRIBED, CHILDREN
  1227. * @param array $select_opts List of selection options (RFC5258: LIST-EXTENDED)
  1228. * Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE,
  1229. * SPECIAL-USE (RFC6154)
  1230. *
  1231. * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
  1232. * is requested, False on error.
  1233. */
  1234. protected function _listMailboxes($ref, $mailbox, $subscribed=false,
  1235. $return_opts=array(), $select_opts=array())
  1236. {
  1237. if (!strlen($mailbox)) {
  1238. $mailbox = '*';
  1239. }
  1240. $args = array();
  1241. $rets = array();
  1242. if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
  1243. $select_opts = (array) $select_opts;
  1244. $args[] = '(' . implode(' ', $select_opts) . ')';
  1245. }
  1246. $args[] = $this->escape($ref);
  1247. $args[] = $this->escape($mailbox);
  1248. if (!empty($return_opts) && $this->getCapability('LIST-EXTENDED')) {
  1249. $ext_opts = array('SUBSCRIBED', 'CHILDREN');
  1250. $rets = array_intersect($return_opts, $ext_opts);
  1251. $return_opts = array_diff($return_opts, $rets);
  1252. }
  1253. if (!empty($return_opts) && $this->getCapability('LIST-STATUS')) {
  1254. $lstatus = true;
  1255. $status_opts = array('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'UNSEEN');
  1256. $opts = array_diff($return_opts, $status_opts);
  1257. $status_opts = array_diff($return_opts, $opts);
  1258. if (!empty($status_opts)) {
  1259. $rets[] = 'STATUS (' . implode(' ', $status_opts) . ')';
  1260. }
  1261. if (!empty($opts)) {
  1262. $rets = array_merge($rets, $opts);
  1263. }
  1264. }
  1265. if (!empty($rets)) {
  1266. $args[] = 'RETURN (' . implode(' ', $rets) . ')';
  1267. }
  1268. list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
  1269. if ($code == self::ERROR_OK) {
  1270. $folders = array();
  1271. $last = 0;
  1272. $pos = 0;
  1273. $response .= "\r\n";
  1274. while ($pos = strpos($response, "\r\n", $pos+1)) {
  1275. // literal string, not real end-of-command-line
  1276. if ($response[$pos-1] == '}') {
  1277. continue;
  1278. }
  1279. $line = substr($response, $last, $pos - $last);
  1280. $last = $pos + 2;
  1281. if (!preg_match('/^\* (LIST|LSUB|STATUS|MYRIGHTS) /i', $line, $m)) {
  1282. continue;
  1283. }
  1284. $cmd = strtoupper($m[1]);
  1285. $line = substr($line, strlen($m[0]));
  1286. // * LIST (<options>) <delimiter> <mailbox>
  1287. if ($cmd == 'LIST' || $cmd == 'LSUB') {
  1288. list($opts, $delim, $mailbox) = $this->tokenizeResponse($line, 3);
  1289. // Remove redundant separator at the end of folder name, UW-IMAP bug? (#1488879)
  1290. if ($delim) {
  1291. $mailbox = rtrim($mailbox, $delim);
  1292. }
  1293. // Add to result array
  1294. if (!$lstatus) {
  1295. $folders[] = $mailbox;
  1296. }
  1297. else {
  1298. $folders[$mailbox] = array();
  1299. }
  1300. // store folder options
  1301. if ($cmd == 'LIST') {
  1302. // Add to options array
  1303. if (empty($this->data['LIST'][$mailbox])) {
  1304. $this->data['LIST'][$mailbox] = $opts;
  1305. }
  1306. else if (!empty($opts)) {
  1307. $this->data['LIST'][$mailbox] = array_unique(array_merge(
  1308. $this->data['LIST'][$mailbox], $opts));
  1309. }
  1310. }
  1311. }
  1312. else if ($lstatus) {
  1313. // * STATUS <mailbox> (<result>)
  1314. if ($cmd == 'STATUS') {
  1315. list($mailbox, $status) = $this->tokenizeResponse($line, 2);
  1316. for ($i=0, $len=count($status); $i<$len; $i += 2) {
  1317. list($name, $value) = $this->tokenizeResponse($status, 2);
  1318. $folders[$mailbox][$name] = $value;
  1319. }
  1320. }
  1321. // * MYRIGHTS <mailbox> <acl>
  1322. else if ($cmd == 'MYRIGHTS') {
  1323. list($mailbox, $acl) = $this->tokenizeResponse($line, 2);
  1324. $folders[$mailbox]['MYRIGHTS'] = $acl;
  1325. }
  1326. }
  1327. }
  1328. return $folders;
  1329. }
  1330. return false;
  1331. }
  1332. /**
  1333. * Returns count of all messages in a folder
  1334. *
  1335. * @param string $mailbox Mailbox name
  1336. *
  1337. * @return int Number of messages, False on error
  1338. */
  1339. public function countMessages($mailbox)
  1340. {
  1341. if ($this->selected === $mailbox && isset($this->data['EXISTS'])) {
  1342. return $this->data['EXISTS'];
  1343. }
  1344. // Check internal cache
  1345. $cache = $this->data['STATUS:'.$mailbox];
  1346. if (!empty($cache) && isset($cache['MESSAGES'])) {
  1347. return (int) $cache['MESSAGES'];
  1348. }
  1349. // Try STATUS (should be faster than SELECT)
  1350. $counts = $this->status($mailbox);
  1351. if (is_array($counts)) {
  1352. return (int) $counts['MESSAGES'];
  1353. }
  1354. return false;
  1355. }
  1356. /**
  1357. * Returns count of messages with \Recent flag in a folder
  1358. *
  1359. * @param string $mailbox Mailbox name
  1360. *
  1361. * @return int Number of messages, False on error
  1362. */
  1363. public function countRecent($mailbox)
  1364. {
  1365. if ($this->selected === $mailbox && isset($this->data['RECENT'])) {
  1366. return $this->data['RECENT'];
  1367. }
  1368. // Check internal cache
  1369. $cache = $this->data['STATUS:'.$mailbox];
  1370. if (!empty($cache) && isset($cache['RECENT'])) {
  1371. return (int) $cache['RECENT'];
  1372. }
  1373. // Try STATUS (should be faster than SELECT)
  1374. $counts = $this->status($mailbox, array('RECENT'));
  1375. if (is_array($counts)) {
  1376. return (int) $counts['RECENT'];
  1377. }
  1378. return false;
  1379. }
  1380. /**
  1381. * Returns count of messages without \Seen flag in a specified folder
  1382. *
  1383. * @param string $mailbox Mailbox name
  1384. *
  1385. * @return int Number of messages, False on error
  1386. */
  1387. public function countUnseen($mailbox)
  1388. {
  1389. // Check internal cache
  1390. $cache = $this->data['STATUS:'.$mailbox];
  1391. if (!empty($cache) && isset($cache['UNSEEN'])) {
  1392. return (int) $cache['UNSEEN'];
  1393. }
  1394. // Try STATUS (should be faster than SELECT+SEARCH)
  1395. $counts = $this->status($mailbox);
  1396. if (is_array($counts)) {
  1397. return (int) $counts['UNSEEN'];
  1398. }
  1399. // Invoke SEARCH as a fallback
  1400. $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
  1401. if (!$index->is_error()) {
  1402. return $index->count();
  1403. }
  1404. return false;
  1405. }
  1406. /**
  1407. * Executes ID command (RFC2971)
  1408. *
  1409. * @param array $items Client identification information key/value hash
  1410. *
  1411. * @return array Server identification information key/value hash
  1412. * @since 0.6
  1413. */
  1414. public function id($items = array())
  1415. {
  1416. if (is_array($items) && !empty($items)) {
  1417. foreach ($items as $key => $value) {
  1418. $args[] = $this->escape($key, true);
  1419. $args[] = $this->escape($value, true);
  1420. }
  1421. }
  1422. list($code, $response) = $this->execute('ID', array(
  1423. !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
  1424. ));
  1425. if ($code == self::ERROR_OK && preg_match('/^\* ID /i', $response)) {
  1426. $response = substr($response, 5); // remove prefix "* ID "
  1427. $items = $this->tokenizeResponse($response, 1);
  1428. $result = null;
  1429. for ($i=0, $len=count($items); $i<$len; $i += 2) {
  1430. $result[$items[$i]] = $items[$i+1];
  1431. }
  1432. return $result;
  1433. }
  1434. return false;
  1435. }
  1436. /**
  1437. * Executes ENABLE command (RFC5161)
  1438. *
  1439. * @param mixed $extension Extension name to enable (or array of names)
  1440. *
  1441. * @return array|bool List of enabled extensions, False on error
  1442. * @since 0.6
  1443. */
  1444. public function enable($extension)
  1445. {
  1446. if (empty($extension)) {
  1447. return false;
  1448. }
  1449. if (!$this->hasCapability('ENABLE')) {
  1450. return false;
  1451. }
  1452. if (!is_array($extension)) {
  1453. $extension = array($extension);
  1454. }
  1455. if (!empty($this->extensions_enabled)) {
  1456. // check if all extensions are already enabled
  1457. $diff = array_diff($extension, $this->extensions_enabled);
  1458. if (empty($diff)) {
  1459. return $extension;
  1460. }
  1461. // Make sure the mailbox isn't selected, before enabling extension(s)
  1462. if ($this->selected !== null) {
  1463. $this->close();
  1464. }
  1465. }
  1466. list($code, $response) = $this->execute('ENABLE', $extension);
  1467. if ($code == self::ERROR_OK && preg_match('/^\* ENABLED /i', $response)) {
  1468. $response = substr($response, 10); // remove prefix "* ENABLED "
  1469. $result = (array) $this->tokenizeResponse($response);
  1470. $this->extensions_enabled = array_unique(array_merge((array)$this->extensions_enabled, $result));
  1471. return $this->extensions_enabled;
  1472. }
  1473. return false;
  1474. }
  1475. /**
  1476. * Executes SORT command
  1477. *
  1478. * @param string $mailbox Mailbox name
  1479. * @param string $field Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
  1480. * @param string $criteria Searching criteria
  1481. * @param bool $return_uid Enables UID SORT usage
  1482. * @param string $encoding Character set
  1483. *
  1484. * @return rcube_result_index Response data
  1485. */
  1486. public function sort($mailbox, $field = 'ARRIVAL', $criteria = '', $return_uid = false, $encoding = 'US-ASCII')
  1487. {
  1488. $old_sel = $this->selected;
  1489. $supported = array('ARRIVAL', 'CC', 'DATE', 'FROM', 'SIZE', 'SUBJECT', 'TO');
  1490. $field = strtoupper($field);
  1491. if ($field == 'INTERNALDATE') {
  1492. $field = 'ARRIVAL';
  1493. }
  1494. if (!in_array($field, $supported)) {
  1495. return new rcube_result_index($mailbox);
  1496. }
  1497. if (!$this->select($mailbox)) {
  1498. return new rcube_result_index($mailbox);
  1499. }
  1500. // return empty result when folder is empty and we're just after SELECT
  1501. if ($old_sel != $mailbox && !$this->data['EXISTS']) {
  1502. return new rcube_result_index($mailbox, '* SORT');
  1503. }
  1504. // RFC 5957: SORT=DISPLAY
  1505. if (($field == 'FROM' || $field == 'TO') && $this->getCapability('SORT=DISPLAY')) {
  1506. $field = 'DISPLAY' . $field;
  1507. }
  1508. $encoding = $encoding ? trim($encoding) : 'US-ASCII';
  1509. $criteria = $criteria ? 'ALL ' . trim($criteria) : 'ALL';
  1510. list($code, $response) = $this->execute($return_uid ? 'UID SORT' : 'SORT',
  1511. array("($field)", $encoding, $criteria));
  1512. if ($code != self::ERROR_OK) {
  1513. $response = null;
  1514. }
  1515. return new rcube_result_index($mailbox, $response);
  1516. }
  1517. /**
  1518. * Executes THREAD command
  1519. *
  1520. * @param string $mailbox Mailbox name
  1521. * @param string $algorithm Threading algorithm (ORDEREDSUBJECT, REFERENCES, REFS)
  1522. * @param string $criteria Searching criteria
  1523. * @param bool $return_uid Enables UIDs in result instead of sequence numbers
  1524. * @param string $encoding Character set
  1525. *
  1526. * @return rcube_result_thread Thread data
  1527. */
  1528. public function thread($mailbox, $algorithm = 'REFERENCES', $criteria = '', $return_uid = false, $encoding = 'US-ASCII')
  1529. {
  1530. $old_sel = $this->selected;
  1531. if (!$this->select($mailbox)) {
  1532. return new rcube_result_thread($mailbox);
  1533. }
  1534. // return empty result when folder is empty and we're just after SELECT
  1535. if ($old_sel != $mailbox && !$this->data['EXISTS']) {
  1536. return new rcube_result_thread($mailbox, '* THREAD');
  1537. }
  1538. $encoding = $encoding ? trim($encoding) : 'US-ASCII';
  1539. $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
  1540. $criteria = $criteria ? 'ALL '.trim($criteria) : 'ALL';
  1541. list($code, $response) = $this->execute($return_uid ? 'UID THREAD' : 'THREAD',
  1542. array($algorithm, $encoding, $criteria));
  1543. if ($code != self::ERROR_OK) {
  1544. $response = null;
  1545. }
  1546. return new rcube_result_thread($mailbox, $response);
  1547. }
  1548. /**
  1549. * Executes SEARCH command
  1550. *
  1551. * @param string $mailbox Mailbox name
  1552. * @param string $criteria Searching criteria
  1553. * @param bool $return_uid Enable UID in result instead of sequence ID
  1554. * @param array $items Return items (MIN, MAX, COUNT, ALL)
  1555. *
  1556. * @return rcube_result_index Result data
  1557. */
  1558. public function search($mailbox, $criteria, $return_uid = false, $items = array())
  1559. {
  1560. $old_sel = $this->selected;
  1561. if (!$this->select($mailbox)) {
  1562. return new rcube_result_index($mailbox);
  1563. }
  1564. // return empty result when folder is empty and we're just after SELECT
  1565. if ($old_sel != $mailbox && !$this->data['EXISTS']) {
  1566. return new rcube_result_index($mailbox, '* SEARCH');
  1567. }
  1568. // If ESEARCH is supported always use ALL
  1569. // but not when items are specified or using simple id2uid search
  1570. if (empty($items) && preg_match('/[^0-9]/', $criteria)) {
  1571. $items = array('ALL');
  1572. }
  1573. $esearch = empty($items) ? false : $this->getCapability('ESEARCH');
  1574. $criteria = trim($criteria);
  1575. $params = '';
  1576. // RFC4731: ESEARCH
  1577. if (!empty($items) && $esearch) {
  1578. $params .= 'RETURN (' . implode(' ', $items) . ')';
  1579. }
  1580. if (!empty($criteria)) {
  1581. $params .= ($params ? ' ' : '') . $criteria;
  1582. }
  1583. else {
  1584. $params .= 'ALL';
  1585. }
  1586. list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
  1587. array($params));
  1588. if ($code != self::ERROR_OK) {
  1589. $response = null;
  1590. }
  1591. return new rcube_result_index($mailbox, $response);
  1592. }
  1593. /**
  1594. * Simulates SORT command by using FETCH and sorting.
  1595. *
  1596. * @param string $mailbox Mailbox name
  1597. * @param string|array $message_set Searching criteria (list of messages to return)
  1598. * @param string $index_field Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
  1599. * @param bool $skip_deleted Makes that DELETED messages will be skipped
  1600. * @param bool $uidfetch Enables UID FETCH usage
  1601. * @param bool $return_uid Enables returning UIDs instead of IDs
  1602. *
  1603. * @return rcube_result_index Response data
  1604. */
  1605. public function index($mailbox, $message_set, $index_field='', $skip_deleted=true,
  1606. $uidfetch=false, $return_uid=false)
  1607. {
  1608. $msg_index = $this->fetchHeaderIndex($mailbox, $message_set,
  1609. $index_field, $skip_deleted, $uidfetch, $return_uid);
  1610. if (!empty($msg_index)) {
  1611. asort($msg_index); // ASC
  1612. $msg_index = array_keys($msg_index);
  1613. $msg_index = '* SEARCH ' . implode(' ', $msg_index);
  1614. }
  1615. else {
  1616. $msg_index = is_array($msg_index) ? '* SEARCH' : null;
  1617. }
  1618. return new rcube_result_index($mailbox, $msg_index);
  1619. }
  1620. /**
  1621. * Fetches specified header/data value for a set of messages.
  1622. *
  1623. * @param string $mailbox Mailbox name
  1624. * @param string|array $message_set Searching criteria (list of messages to return)
  1625. * @param string $index_field Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
  1626. * @param bool $skip_deleted Makes that DELETED messages will be skipped
  1627. * @param bool $uidfetch Enables UID FETCH usage
  1628. * @param bool $return_uid Enables returning UIDs instead of IDs
  1629. *
  1630. * @return array|bool List of header values or False on failure
  1631. */
  1632. public function fetchHeaderIndex($mailbox, $message_set, $index_field = '', $skip_deleted = true,
  1633. $uidfetch = false, $return_uid = false)
  1634. {
  1635. if (is_array($message_set)) {
  1636. if (!($message_set = $this->compressMessageSet($message_set))) {
  1637. return false;
  1638. }
  1639. }
  1640. else {
  1641. list($from_idx, $to_idx) = explode(':', $message_set);
  1642. if (empty($message_set) ||
  1643. (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)
  1644. ) {
  1645. return false;
  1646. }
  1647. }
  1648. $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
  1649. $fields_a['DATE'] = 1;
  1650. $fields_a['INTERNALDATE'] = 4;
  1651. $fields_a['ARRIVAL'] = 4;
  1652. $fields_a['FROM'] = 1;
  1653. $fields_a['REPLY-TO'] = 1;
  1654. $fields_a['SENDER'] = 1;
  1655. $fields_a['TO'] = 1;
  1656. $fields_a['CC'] = 1;
  1657. $fields_a['SUBJECT'] = 1;
  1658. $fields_a['UID'] = 2;
  1659. $fields_a['SIZE'] = 2;
  1660. $fields_a['SEEN'] = 3;
  1661. $fields_a['RECENT'] = 3;
  1662. $fields_a['DELETED'] = 3;
  1663. if (!($mode = $fields_a[$index_field])) {
  1664. return false;
  1665. }
  1666. // Select the mailbox
  1667. if (!$this->select($mailbox)) {
  1668. return false;
  1669. }
  1670. // build FETCH command string
  1671. $key = $this->nextTag();
  1672. $cmd = $uidfetch ? 'UID FETCH' : 'FETCH';
  1673. $fields = array();
  1674. if ($return_uid) {
  1675. $fields[] = 'UID';
  1676. }
  1677. if ($skip_deleted) {
  1678. $fields[] = 'FLAGS';
  1679. }
  1680. if ($mode == 1) {
  1681. if ($index_field == 'DATE') {
  1682. $fields[] = 'INTERNALDATE';
  1683. }
  1684. $fields[] = "BODY.PEEK[HEADER.FIELDS ($index_field)]";
  1685. }
  1686. else if ($mode == 2) {
  1687. if ($index_field == 'SIZE') {
  1688. $fields[] = 'RFC822.SIZE';
  1689. }
  1690. else if (!$return_uid || $index_field != 'UID') {
  1691. $fields[] = $index_field;
  1692. }
  1693. }
  1694. else if ($mode == 3 && !$skip_deleted) {
  1695. $fields[] = 'FLAGS';
  1696. }
  1697. else if ($mode == 4) {
  1698. $fields[] = 'INTERNALDATE';
  1699. }
  1700. $request = "$key $cmd $message_set (" . implode(' ', $fields) . ")";
  1701. if (!$this->putLine($request)) {
  1702. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  1703. return false;
  1704. }
  1705. $result = array();
  1706. do {
  1707. $line = rtrim($this->readLine(200));
  1708. $line = $this->multLine($line);
  1709. if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
  1710. $id = $m[1];
  1711. $flags = null;
  1712. if ($return_uid) {
  1713. if (preg_match('/UID ([0-9]+)/', $line, $matches)) {
  1714. $id = (int) $matches[1];
  1715. }
  1716. else {
  1717. continue;
  1718. }
  1719. }
  1720. if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
  1721. $flags = explode(' ', strtoupper($matches[1]));
  1722. if (in_array('\\DELETED', $flags)) {
  1723. continue;
  1724. }
  1725. }
  1726. if ($mode == 1 && $index_field == 'DATE') {
  1727. if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
  1728. $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
  1729. $value = trim($value);
  1730. $result[$id] = $this->strToTime($value);
  1731. }
  1732. // non-existent/empty Date: header, use INTERNALDATE
  1733. if (empty($result[$id])) {
  1734. if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
  1735. $result[$id] = $this->strToTime($matches[1]);
  1736. }
  1737. else {
  1738. $result[$id] = 0;
  1739. }
  1740. }
  1741. }
  1742. else if ($mode == 1) {
  1743. if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
  1744. $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
  1745. $result[$id] = trim($value);
  1746. }
  1747. else {
  1748. $result[$id] = '';
  1749. }
  1750. }
  1751. else if ($mode == 2) {
  1752. if (preg_match('/' . $index_field . ' ([0-9]+)/', $line, $matches)) {
  1753. $result[$id] = trim($matches[1]);
  1754. }
  1755. else {
  1756. $result[$id] = 0;
  1757. }
  1758. }
  1759. else if ($mode == 3) {
  1760. if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
  1761. $flags = explode(' ', $matches[1]);
  1762. }
  1763. $result[$id] = in_array("\\".$index_field, (array) $flags) ? 1 : 0;
  1764. }
  1765. else if ($mode == 4) {
  1766. if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
  1767. $result[$id] = $this->strToTime($matches[1]);
  1768. }
  1769. else {
  1770. $result[$id] = 0;
  1771. }
  1772. }
  1773. }
  1774. }
  1775. while (!$this->startsWith($line, $key, true, true));
  1776. return $result;
  1777. }
  1778. /**
  1779. * Returns message sequence identifier
  1780. *
  1781. * @param string $mailbox Mailbox name
  1782. * @param int $uid Message unique identifier (UID)
  1783. *
  1784. * @return int Message sequence identifier
  1785. */
  1786. public function UID2ID($mailbox, $uid)
  1787. {
  1788. if ($uid > 0) {
  1789. $index = $this->search($mailbox, "UID $uid");
  1790. if ($index->count() == 1) {
  1791. $arr = $index->get();
  1792. return (int) $arr[0];
  1793. }
  1794. }
  1795. }
  1796. /**
  1797. * Returns message unique identifier (UID)
  1798. *
  1799. * @param string $mailbox Mailbox name
  1800. * @param int $uid Message sequence identifier
  1801. *
  1802. * @return int Message unique identifier
  1803. */
  1804. public function ID2UID($mailbox, $id)
  1805. {
  1806. if (empty($id) || $id < 0) {
  1807. return null;
  1808. }
  1809. if (!$this->select($mailbox)) {
  1810. return null;
  1811. }
  1812. if ($uid = $this->data['UID-MAP'][$id]) {
  1813. return $uid;
  1814. }
  1815. if (isset($this->data['EXISTS']) && $id > $this->data['EXISTS']) {
  1816. return null;
  1817. }
  1818. $index = $this->search($mailbox, $id, true);
  1819. if ($index->count() == 1) {
  1820. $arr = $index->get();
  1821. return $this->data['UID-MAP'][$id] = (int) $arr[0];
  1822. }
  1823. }
  1824. /**
  1825. * Sets flag of the message(s)
  1826. *
  1827. * @param string $mailbox Mailbox name
  1828. * @param string|array $messages Message UID(s)
  1829. * @param string $flag Flag name
  1830. *
  1831. * @return bool True on success, False on failure
  1832. */
  1833. public function flag($mailbox, $messages, $flag)
  1834. {
  1835. return $this->modFlag($mailbox, $messages, $flag, '+');
  1836. }
  1837. /**
  1838. * Unsets flag of the message(s)
  1839. *
  1840. * @param string $mailbox Mailbox name
  1841. * @param string|array $messages Message UID(s)
  1842. * @param string $flag Flag name
  1843. *
  1844. * @return bool True on success, False on failure
  1845. */
  1846. public function unflag($mailbox, $messages, $flag)
  1847. {
  1848. return $this->modFlag($mailbox, $messages, $flag, '-');
  1849. }
  1850. /**
  1851. * Changes flag of the message(s)
  1852. *
  1853. * @param string $mailbox Mailbox name
  1854. * @param string|array $messages Message UID(s)
  1855. * @param string $flag Flag name
  1856. * @param string $mod Modifier [+|-]. Default: "+".
  1857. *
  1858. * @return bool True on success, False on failure
  1859. */
  1860. protected function modFlag($mailbox, $messages, $flag, $mod = '+')
  1861. {
  1862. if (!$flag) {
  1863. return false;
  1864. }
  1865. if (!$this->select($mailbox)) {
  1866. return false;
  1867. }
  1868. if (!$this->data['READ-WRITE']) {
  1869. $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
  1870. return false;
  1871. }
  1872. if ($this->flags[strtoupper($flag)]) {
  1873. $flag = $this->flags[strtoupper($flag)];
  1874. }
  1875. // if PERMANENTFLAGS is not specified all flags are allowed
  1876. if (!empty($this->data['PERMANENTFLAGS'])
  1877. && !in_array($flag, (array) $this->data['PERMANENTFLAGS'])
  1878. && !in_array('\\*', (array) $this->data['PERMANENTFLAGS'])
  1879. ) {
  1880. return false;
  1881. }
  1882. // Clear internal status cache
  1883. if ($flag == 'SEEN') {
  1884. unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
  1885. }
  1886. if ($mod != '+' && $mod != '-') {
  1887. $mod = '+';
  1888. }
  1889. $result = $this->execute('UID STORE', array(
  1890. $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
  1891. self::COMMAND_NORESPONSE);
  1892. return $result == self::ERROR_OK;
  1893. }
  1894. /**
  1895. * Copies message(s) from one folder to another
  1896. *
  1897. * @param string|array $messages Message UID(s)
  1898. * @param string $from Mailbox name
  1899. * @param string $to Destination mailbox name
  1900. *
  1901. * @return bool True on success, False on failure
  1902. */
  1903. public function copy($messages, $from, $to)
  1904. {
  1905. // Clear last COPYUID data
  1906. unset($this->data['COPYUID']);
  1907. if (!$this->select($from)) {
  1908. return false;
  1909. }
  1910. // Clear internal status cache
  1911. unset($this->data['STATUS:'.$to]);
  1912. $result = $this->execute('UID COPY', array(
  1913. $this->compressMessageSet($messages), $this->escape($to)),
  1914. self::COMMAND_NORESPONSE);
  1915. return $result == self::ERROR_OK;
  1916. }
  1917. /**
  1918. * Moves message(s) from one folder to another.
  1919. *
  1920. * @param string|array $messages Message UID(s)
  1921. * @param string $from Mailbox name
  1922. * @param string $to Destination mailbox name
  1923. *
  1924. * @return bool True on success, False on failure
  1925. */
  1926. public function move($messages, $from, $to)
  1927. {
  1928. if (!$this->select($from)) {
  1929. return false;
  1930. }
  1931. if (!$this->data['READ-WRITE']) {
  1932. $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
  1933. return false;
  1934. }
  1935. // use MOVE command (RFC 6851)
  1936. if ($this->hasCapability('MOVE')) {
  1937. // Clear last COPYUID data
  1938. unset($this->data['COPYUID']);
  1939. // Clear internal status cache
  1940. unset($this->data['STATUS:'.$to]);
  1941. $this->clear_status_cache($from);
  1942. $result = $this->execute('UID MOVE', array(
  1943. $this->compressMessageSet($messages), $this->escape($to)),
  1944. self::COMMAND_NORESPONSE);
  1945. return $result == self::ERROR_OK;
  1946. }
  1947. // use COPY + STORE +FLAGS.SILENT \Deleted + EXPUNGE
  1948. $result = $this->copy($messages, $from, $to);
  1949. if ($result) {
  1950. // Clear internal status cache
  1951. unset($this->data['STATUS:'.$from]);
  1952. $result = $this->flag($from, $messages, 'DELETED');
  1953. if ($messages == '*') {
  1954. // CLOSE+SELECT should be faster than EXPUNGE
  1955. $this->close();
  1956. }
  1957. else {
  1958. $this->expunge($from, $messages);
  1959. }
  1960. }
  1961. return $result;
  1962. }
  1963. /**
  1964. * FETCH command (RFC3501)
  1965. *
  1966. * @param string $mailbox Mailbox name
  1967. * @param mixed $message_set Message(s) sequence identifier(s) or UID(s)
  1968. * @param bool $is_uid True if $message_set contains UIDs
  1969. * @param array $query_items FETCH command data items
  1970. * @param string $mod_seq Modification sequence for CHANGEDSINCE (RFC4551) query
  1971. * @param bool $vanished Enables VANISHED parameter (RFC5162) for CHANGEDSINCE query
  1972. *
  1973. * @return array List of rcube_message_header elements, False on error
  1974. * @since 0.6
  1975. */
  1976. public function fetch($mailbox, $message_set, $is_uid = false, $query_items = array(),
  1977. $mod_seq = null, $vanished = false)
  1978. {
  1979. if (!$this->select($mailbox)) {
  1980. return false;
  1981. }
  1982. $message_set = $this->compressMessageSet($message_set);
  1983. $result = array();
  1984. $key = $this->nextTag();
  1985. $request = $key . ($is_uid ? ' UID' : '') . " FETCH $message_set ";
  1986. $request .= "(" . implode(' ', $query_items) . ")";
  1987. if ($mod_seq !== null && $this->hasCapability('CONDSTORE')) {
  1988. $request .= " (CHANGEDSINCE $mod_seq" . ($vanished ? " VANISHED" : '') .")";
  1989. }
  1990. if (!$this->putLine($request)) {
  1991. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  1992. return false;
  1993. }
  1994. do {
  1995. $line = $this->readLine(4096);
  1996. if (!$line) {
  1997. break;
  1998. }
  1999. // Sample reply line:
  2000. // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
  2001. // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
  2002. // BODY[HEADER.FIELDS ...
  2003. if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
  2004. $id = intval($m[1]);
  2005. $result[$id] = new rcube_message_header;
  2006. $result[$id]->id = $id;
  2007. $result[$id]->subject = '';
  2008. $result[$id]->messageID = 'mid:' . $id;
  2009. $headers = null;
  2010. $lines = array();
  2011. $line = substr($line, strlen($m[0]) + 2);
  2012. $ln = 0;
  2013. // get complete entry
  2014. while (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
  2015. $bytes = $m[1];
  2016. $out = '';
  2017. while (strlen($out) < $bytes) {
  2018. $out = $this->readBytes($bytes);
  2019. if ($out === null) {
  2020. break;
  2021. }
  2022. $line .= $out;
  2023. }
  2024. $str = $this->readLine(4096);
  2025. if ($str === false) {
  2026. break;
  2027. }
  2028. $line .= $str;
  2029. }
  2030. // Tokenize response and assign to object properties
  2031. while (list($name, $value) = $this->tokenizeResponse($line, 2)) {
  2032. if ($name == 'UID') {
  2033. $result[$id]->uid = intval($value);
  2034. }
  2035. else if ($name == 'RFC822.SIZE') {
  2036. $result[$id]->size = intval($value);
  2037. }
  2038. else if ($name == 'RFC822.TEXT') {
  2039. $result[$id]->body = $value;
  2040. }
  2041. else if ($name == 'INTERNALDATE') {
  2042. $result[$id]->internaldate = $value;
  2043. $result[$id]->date = $value;
  2044. $result[$id]->timestamp = $this->StrToTime($value);
  2045. }
  2046. else if ($name == 'FLAGS') {
  2047. if (!empty($value)) {
  2048. foreach ((array)$value as $flag) {
  2049. $flag = str_replace(array('$', "\\"), '', $flag);
  2050. $flag = strtoupper($flag);
  2051. $result[$id]->flags[$flag] = true;
  2052. }
  2053. }
  2054. }
  2055. else if ($name == 'MODSEQ') {
  2056. $result[$id]->modseq = $value[0];
  2057. }
  2058. else if ($name == 'ENVELOPE') {
  2059. $result[$id]->envelope = $value;
  2060. }
  2061. else if ($name == 'BODYSTRUCTURE' || ($name == 'BODY' && count($value) > 2)) {
  2062. if (!is_array($value[0]) && (strtolower($value[0]) == 'message' && strtolower($value[1]) == 'rfc822')) {
  2063. $value = array($value);
  2064. }
  2065. $result[$id]->bodystructure = $value;
  2066. }
  2067. else if ($name == 'RFC822') {
  2068. $result[$id]->body = $value;
  2069. }
  2070. else if (stripos($name, 'BODY[') === 0) {
  2071. $name = str_replace(']', '', substr($name, 5));
  2072. if ($name == 'HEADER.FIELDS') {
  2073. // skip ']' after headers list
  2074. $this->tokenizeResponse($line, 1);
  2075. $headers = $this->tokenizeResponse($line, 1);
  2076. }
  2077. else if (strlen($name)) {
  2078. $result[$id]->bodypart[$name] = $value;
  2079. }
  2080. else {
  2081. $result[$id]->body = $value;
  2082. }
  2083. }
  2084. }
  2085. // create array with header field:data
  2086. if (!empty($headers)) {
  2087. $headers = explode("\n", trim($headers));
  2088. foreach ($headers as $resln) {
  2089. if (ord($resln[0]) <= 32) {
  2090. $lines[$ln] .= (empty($lines[$ln]) ? '' : "\n") . trim($resln);
  2091. }
  2092. else {
  2093. $lines[++$ln] = trim($resln);
  2094. }
  2095. }
  2096. foreach ($lines as $str) {
  2097. list($field, $string) = explode(':', $str, 2);
  2098. $field = strtolower($field);
  2099. $string = preg_replace('/\n[\t\s]*/', ' ', trim($string));
  2100. switch ($field) {
  2101. case 'date';
  2102. $result[$id]->date = $string;
  2103. $result[$id]->timestamp = $this->strToTime($string);
  2104. break;
  2105. case 'to':
  2106. $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
  2107. break;
  2108. case 'from':
  2109. case 'subject':
  2110. case 'cc':
  2111. case 'bcc':
  2112. case 'references':
  2113. $result[$id]->{$field} = $string;
  2114. break;
  2115. case 'reply-to':
  2116. $result[$id]->replyto = $string;
  2117. break;
  2118. case 'content-transfer-encoding':
  2119. $result[$id]->encoding = $string;
  2120. break;
  2121. case 'content-type':
  2122. $ctype_parts = preg_split('/[; ]+/', $string);
  2123. $result[$id]->ctype = strtolower(array_shift($ctype_parts));
  2124. if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
  2125. $result[$id]->charset = $regs[1];
  2126. }
  2127. break;
  2128. case 'in-reply-to':
  2129. $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
  2130. break;
  2131. case 'return-receipt-to':
  2132. case 'disposition-notification-to':
  2133. case 'x-confirm-reading-to':
  2134. $result[$id]->mdn_to = $string;
  2135. break;
  2136. case 'message-id':
  2137. $result[$id]->messageID = $string;
  2138. break;
  2139. case 'x-priority':
  2140. if (preg_match('/^(\d+)/', $string, $matches)) {
  2141. $result[$id]->priority = intval($matches[1]);
  2142. }
  2143. break;
  2144. default:
  2145. if (strlen($field) < 3) {
  2146. break;
  2147. }
  2148. if ($result[$id]->others[$field]) {
  2149. $string = array_merge((array)$result[$id]->others[$field], (array)$string);
  2150. }
  2151. $result[$id]->others[$field] = $string;
  2152. }
  2153. }
  2154. }
  2155. }
  2156. // VANISHED response (QRESYNC RFC5162)
  2157. // Sample: * VANISHED (EARLIER) 300:310,405,411
  2158. else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
  2159. $line = substr($line, strlen($match[0]));
  2160. $v_data = $this->tokenizeResponse($line, 1);
  2161. $this->data['VANISHED'] = $v_data;
  2162. }
  2163. }
  2164. while (!$this->startsWith($line, $key, true));
  2165. return $result;
  2166. }
  2167. /**
  2168. * Returns message(s) data (flags, headers, etc.)
  2169. *
  2170. * @param string $mailbox Mailbox name
  2171. * @param mixed $message_set Message(s) sequence identifier(s) or UID(s)
  2172. * @param bool $is_uid True if $message_set contains UIDs
  2173. * @param bool $bodystr Enable to add BODYSTRUCTURE data to the result
  2174. * @param array $add_headers List of additional headers
  2175. *
  2176. * @return bool|array List of rcube_message_header elements, False on error
  2177. */
  2178. public function fetchHeaders($mailbox, $message_set, $is_uid = false, $bodystr = false, $add_headers = array())
  2179. {
  2180. $query_items = array('UID', 'RFC822.SIZE', 'FLAGS', 'INTERNALDATE');
  2181. $headers = array('DATE', 'FROM', 'TO', 'SUBJECT', 'CONTENT-TYPE', 'CC', 'REPLY-TO',
  2182. 'LIST-POST', 'DISPOSITION-NOTIFICATION-TO', 'X-PRIORITY');
  2183. if (!empty($add_headers)) {
  2184. $add_headers = array_map('strtoupper', $add_headers);
  2185. $headers = array_unique(array_merge($headers, $add_headers));
  2186. }
  2187. if ($bodystr) {
  2188. $query_items[] = 'BODYSTRUCTURE';
  2189. }
  2190. $query_items[] = 'BODY.PEEK[HEADER.FIELDS (' . implode(' ', $headers) . ')]';
  2191. return $this->fetch($mailbox, $message_set, $is_uid, $query_items);
  2192. }
  2193. /**
  2194. * Returns message data (flags, headers, etc.)
  2195. *
  2196. * @param string $mailbox Mailbox name
  2197. * @param int $id Message sequence identifier or UID
  2198. * @param bool $is_uid True if $id is an UID
  2199. * @param bool $bodystr Enable to add BODYSTRUCTURE data to the result
  2200. * @param array $add_headers List of additional headers
  2201. *
  2202. * @return bool|rcube_message_header Message data, False on error
  2203. */
  2204. public function fetchHeader($mailbox, $id, $is_uid = false, $bodystr = false, $add_headers = array())
  2205. {
  2206. $a = $this->fetchHeaders($mailbox, $id, $is_uid, $bodystr, $add_headers);
  2207. if (is_array($a)) {
  2208. return array_shift($a);
  2209. }
  2210. return false;
  2211. }
  2212. /**
  2213. * Sort messages by specified header field
  2214. *
  2215. * @param array $messages Array of rcube_message_header objects
  2216. * @param string $field Name of the property to sort by
  2217. * @param string $flag Sorting order (ASC|DESC)
  2218. *
  2219. * @return array Sorted input array
  2220. */
  2221. public static function sortHeaders($messages, $field, $flag)
  2222. {
  2223. // Strategy: First, we'll create an "index" array.
  2224. // Then, we'll use sort() on that array, and use that to sort the main array.
  2225. $field = empty($field) ? 'uid' : strtolower($field);
  2226. $flag = empty($flag) ? 'ASC' : strtoupper($flag);
  2227. $index = array();
  2228. $result = array();
  2229. reset($messages);
  2230. while (list($key, $headers) = each($messages)) {
  2231. $value = null;
  2232. switch ($field) {
  2233. case 'arrival':
  2234. $field = 'internaldate';
  2235. case 'date':
  2236. case 'internaldate':
  2237. case 'timestamp':
  2238. $value = self::strToTime($headers->$field);
  2239. if (!$value && $field != 'timestamp') {
  2240. $value = $headers->timestamp;
  2241. }
  2242. break;
  2243. default:
  2244. // @TODO: decode header value, convert to UTF-8
  2245. $value = $headers->$field;
  2246. if (is_string($value)) {
  2247. $value = str_replace('"', '', $value);
  2248. if ($field == 'subject') {
  2249. $value = preg_replace('/^(Re:\s*|Fwd:\s*|Fw:\s*)+/i', '', $value);
  2250. }
  2251. $data = strtoupper($value);
  2252. }
  2253. }
  2254. $index[$key] = $value;
  2255. }
  2256. if (!empty($index)) {
  2257. // sort index
  2258. if ($flag == 'ASC') {
  2259. asort($index);
  2260. }
  2261. else {
  2262. arsort($index);
  2263. }
  2264. // form new array based on index
  2265. while (list($key, $val) = each($index)) {
  2266. $result[$key] = $messages[$key];
  2267. }
  2268. }
  2269. return $result;
  2270. }
  2271. /**
  2272. * Fetch MIME headers of specified message parts
  2273. *
  2274. * @param string $mailbox Mailbox name
  2275. * @param int $uid Message UID
  2276. * @param array $parts Message part identifiers
  2277. * @param bool $mime Use MIME instad of HEADER
  2278. *
  2279. * @return array|bool Array containing headers string for each specified body
  2280. * False on failure.
  2281. */
  2282. public function fetchMIMEHeaders($mailbox, $uid, $parts, $mime = true)
  2283. {
  2284. if (!$this->select($mailbox)) {
  2285. return false;
  2286. }
  2287. $result = false;
  2288. $parts = (array) $parts;
  2289. $key = $this->nextTag();
  2290. $peeks = array();
  2291. $type = $mime ? 'MIME' : 'HEADER';
  2292. // format request
  2293. foreach ($parts as $part) {
  2294. $peeks[] = "BODY.PEEK[$part.$type]";
  2295. }
  2296. $request = "$key UID FETCH $uid (" . implode(' ', $peeks) . ')';
  2297. // send request
  2298. if (!$this->putLine($request)) {
  2299. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  2300. return false;
  2301. }
  2302. do {
  2303. $line = $this->readLine(1024);
  2304. if (preg_match('/^\* [0-9]+ FETCH [0-9UID( ]+/', $line, $m)) {
  2305. $line = ltrim(substr($line, strlen($m[0])));
  2306. while (preg_match('/^BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
  2307. $line = substr($line, strlen($matches[0]));
  2308. $result[$matches[1]] = trim($this->multLine($line));
  2309. $line = $this->readLine(1024);
  2310. }
  2311. }
  2312. }
  2313. while (!$this->startsWith($line, $key, true));
  2314. return $result;
  2315. }
  2316. /**
  2317. * Fetches message part header
  2318. */
  2319. public function fetchPartHeader($mailbox, $id, $is_uid = false, $part = null)
  2320. {
  2321. $part = empty($part) ? 'HEADER' : $part.'.MIME';
  2322. return $this->handlePartBody($mailbox, $id, $is_uid, $part);
  2323. }
  2324. /**
  2325. * Fetches body of the specified message part
  2326. */
  2327. public function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=null, $print=null, $file=null, $formatted=false, $max_bytes=0)
  2328. {
  2329. if (!$this->select($mailbox)) {
  2330. return false;
  2331. }
  2332. $binary = true;
  2333. do {
  2334. if (!$initiated) {
  2335. switch ($encoding) {
  2336. case 'base64':
  2337. $mode = 1;
  2338. break;
  2339. case 'quoted-printable':
  2340. $mode = 2;
  2341. break;
  2342. case 'x-uuencode':
  2343. case 'x-uue':
  2344. case 'uue':
  2345. case 'uuencode':
  2346. $mode = 3;
  2347. break;
  2348. default:
  2349. $mode = 0;
  2350. }
  2351. // Use BINARY extension when possible (and safe)
  2352. $binary = $binary && $mode && preg_match('/^[0-9.]+$/', $part) && $this->hasCapability('BINARY');
  2353. $fetch_mode = $binary ? 'BINARY' : 'BODY';
  2354. $partial = $max_bytes ? sprintf('<0.%d>', $max_bytes) : '';
  2355. // format request
  2356. $key = $this->nextTag();
  2357. $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id ($fetch_mode.PEEK[$part]$partial)";
  2358. $result = false;
  2359. $found = false;
  2360. $initiated = true;
  2361. // send request
  2362. if (!$this->putLine($request)) {
  2363. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  2364. return false;
  2365. }
  2366. if ($binary) {
  2367. // WARNING: Use $formatted argument with care, this may break binary data stream
  2368. $mode = -1;
  2369. }
  2370. }
  2371. $line = trim($this->readLine(1024));
  2372. if (!$line) {
  2373. break;
  2374. }
  2375. // handle UNKNOWN-CTE response - RFC 3516, try again with standard BODY request
  2376. if ($binary && !$found && preg_match('/^' . $key . ' NO \[UNKNOWN-CTE\]/i', $line)) {
  2377. $binary = $initiated = false;
  2378. continue;
  2379. }
  2380. // skip irrelevant untagged responses (we have a result already)
  2381. if ($found || !preg_match('/^\* ([0-9]+) FETCH (.*)$/', $line, $m)) {
  2382. continue;
  2383. }
  2384. $line = $m[2];
  2385. // handle one line response
  2386. if ($line[0] == '(' && substr($line, -1) == ')') {
  2387. // tokenize content inside brackets
  2388. // the content can be e.g.: (UID 9844 BODY[2.4] NIL)
  2389. $tokens = $this->tokenizeResponse(preg_replace('/(^\(|\)$)/', '', $line));
  2390. for ($i=0; $i<count($tokens); $i+=2) {
  2391. if (preg_match('/^(BODY|BINARY)/i', $tokens[$i])) {
  2392. $result = $tokens[$i+1];
  2393. $found = true;
  2394. break;
  2395. }
  2396. }
  2397. if ($result !== false) {
  2398. if ($mode == 1) {
  2399. $result = base64_decode($result);
  2400. }
  2401. else if ($mode == 2) {
  2402. $result = quoted_printable_decode($result);
  2403. }
  2404. else if ($mode == 3) {
  2405. $result = convert_uudecode($result);
  2406. }
  2407. }
  2408. }
  2409. // response with string literal
  2410. else if (preg_match('/\{([0-9]+)\}$/', $line, $m)) {
  2411. $bytes = (int) $m[1];
  2412. $prev = '';
  2413. $found = true;
  2414. // empty body
  2415. if (!$bytes) {
  2416. $result = '';
  2417. }
  2418. else while ($bytes > 0) {
  2419. $line = $this->readLine(8192);
  2420. if ($line === null) {
  2421. break;
  2422. }
  2423. $len = strlen($line);
  2424. if ($len > $bytes) {
  2425. $line = substr($line, 0, $bytes);
  2426. $len = strlen($line);
  2427. }
  2428. $bytes -= $len;
  2429. // BASE64
  2430. if ($mode == 1) {
  2431. $line = preg_replace('|[^a-zA-Z0-9+=/]|', '', $line);
  2432. // create chunks with proper length for base64 decoding
  2433. $line = $prev.$line;
  2434. $length = strlen($line);
  2435. if ($length % 4) {
  2436. $length = floor($length / 4) * 4;
  2437. $prev = substr($line, $length);
  2438. $line = substr($line, 0, $length);
  2439. }
  2440. else {
  2441. $prev = '';
  2442. }
  2443. $line = base64_decode($line);
  2444. }
  2445. // QUOTED-PRINTABLE
  2446. else if ($mode == 2) {
  2447. $line = rtrim($line, "\t\r\0\x0B");
  2448. $line = quoted_printable_decode($line);
  2449. }
  2450. // UUENCODE
  2451. else if ($mode == 3) {
  2452. $line = rtrim($line, "\t\r\n\0\x0B");
  2453. if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line)) {
  2454. continue;
  2455. }
  2456. $line = convert_uudecode($line);
  2457. }
  2458. // default
  2459. else if ($formatted) {
  2460. $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
  2461. }
  2462. if ($file) {
  2463. if (fwrite($file, $line) === false) {
  2464. break;
  2465. }
  2466. }
  2467. else if ($print) {
  2468. echo $line;
  2469. }
  2470. else {
  2471. $result .= $line;
  2472. }
  2473. }
  2474. }
  2475. }
  2476. while (!$this->startsWith($line, $key, true) || !$initiated);
  2477. if ($result !== false) {
  2478. if ($file) {
  2479. return fwrite($file, $result);
  2480. }
  2481. else if ($print) {
  2482. echo $result;
  2483. return true;
  2484. }
  2485. return $result;
  2486. }
  2487. return false;
  2488. }
  2489. /**
  2490. * Handler for IMAP APPEND command
  2491. *
  2492. * @param string $mailbox Mailbox name
  2493. * @param string|array $message The message source string or array (of strings and file pointers)
  2494. * @param array $flags Message flags
  2495. * @param string $date Message internal date
  2496. * @param bool $binary Enable BINARY append (RFC3516)
  2497. *
  2498. * @return string|bool On success APPENDUID response (if available) or True, False on failure
  2499. */
  2500. public function append($mailbox, &$message, $flags = array(), $date = null, $binary = false)
  2501. {
  2502. unset($this->data['APPENDUID']);
  2503. if ($mailbox === null || $mailbox === '') {
  2504. return false;
  2505. }
  2506. $binary = $binary && $this->getCapability('BINARY');
  2507. $literal_plus = !$binary && $this->prefs['literal+'];
  2508. $len = 0;
  2509. $msg = is_array($message) ? $message : array(&$message);
  2510. $chunk_size = 512000;
  2511. for ($i=0, $cnt=count($msg); $i<$cnt; $i++) {
  2512. if (is_resource($msg[$i])) {
  2513. $stat = fstat($msg[$i]);
  2514. if ($stat === false) {
  2515. return false;
  2516. }
  2517. $len += $stat['size'];
  2518. }
  2519. else {
  2520. if (!$binary) {
  2521. $msg[$i] = str_replace("\r", '', $msg[$i]);
  2522. $msg[$i] = str_replace("\n", "\r\n", $msg[$i]);
  2523. }
  2524. $len += strlen($msg[$i]);
  2525. }
  2526. }
  2527. if (!$len) {
  2528. return false;
  2529. }
  2530. // build APPEND command
  2531. $key = $this->nextTag();
  2532. $request = "$key APPEND " . $this->escape($mailbox) . ' (' . $this->flagsToStr($flags) . ')';
  2533. if (!empty($date)) {
  2534. $request .= ' ' . $this->escape($date);
  2535. }
  2536. $request .= ' ' . ($binary ? '~' : '') . '{' . $len . ($literal_plus ? '+' : '') . '}';
  2537. // send APPEND command
  2538. if ($this->putLine($request)) {
  2539. // Do not wait when LITERAL+ is supported
  2540. if (!$literal_plus) {
  2541. $line = $this->readReply();
  2542. if ($line[0] != '+') {
  2543. $this->parseResult($line, 'APPEND: ');
  2544. return false;
  2545. }
  2546. }
  2547. foreach ($msg as $msg_part) {
  2548. // file pointer
  2549. if (is_resource($msg_part)) {
  2550. rewind($msg_part);
  2551. while (!feof($msg_part) && $this->fp) {
  2552. $buffer = fread($msg_part, $chunk_size);
  2553. $this->putLine($buffer, false);
  2554. }
  2555. fclose($msg_part);
  2556. }
  2557. // string
  2558. else {
  2559. $size = strlen($msg_part);
  2560. // Break up the data by sending one chunk (up to 512k) at a time.
  2561. // This approach reduces our peak memory usage
  2562. for ($offset = 0; $offset < $size; $offset += $chunk_size) {
  2563. $chunk = substr($msg_part, $offset, $chunk_size);
  2564. if (!$this->putLine($chunk, false)) {
  2565. return false;
  2566. }
  2567. }
  2568. }
  2569. }
  2570. if (!$this->putLine('')) { // \r\n
  2571. return false;
  2572. }
  2573. do {
  2574. $line = $this->readLine();
  2575. } while (!$this->startsWith($line, $key, true, true));
  2576. // Clear internal status cache
  2577. unset($this->data['STATUS:'.$mailbox]);
  2578. if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
  2579. return false;
  2580. else if (!empty($this->data['APPENDUID']))
  2581. return $this->data['APPENDUID'];
  2582. else
  2583. return true;
  2584. }
  2585. else {
  2586. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  2587. }
  2588. return false;
  2589. }
  2590. /**
  2591. * Handler for IMAP APPEND command.
  2592. *
  2593. * @param string $mailbox Mailbox name
  2594. * @param string $path Path to the file with message body
  2595. * @param string $headers Message headers
  2596. * @param array $flags Message flags
  2597. * @param string $date Message internal date
  2598. * @param bool $binary Enable BINARY append (RFC3516)
  2599. *
  2600. * @return string|bool On success APPENDUID response (if available) or True, False on failure
  2601. */
  2602. public function appendFromFile($mailbox, $path, $headers=null, $flags = array(), $date = null, $binary = false)
  2603. {
  2604. // open message file
  2605. if (file_exists(realpath($path))) {
  2606. $fp = fopen($path, 'r');
  2607. }
  2608. if (!$fp) {
  2609. $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
  2610. return false;
  2611. }
  2612. $message = array();
  2613. if ($headers) {
  2614. $message[] = trim($headers, "\r\n") . "\r\n\r\n";
  2615. }
  2616. $message[] = $fp;
  2617. return $this->append($mailbox, $message, $flags, $date, $binary);
  2618. }
  2619. /**
  2620. * Returns QUOTA information
  2621. *
  2622. * @param string $mailbox Mailbox name
  2623. *
  2624. * @return array Quota information
  2625. */
  2626. public function getQuota($mailbox = null)
  2627. {
  2628. if ($mailbox === null || $mailbox === '') {
  2629. $mailbox = 'INBOX';
  2630. }
  2631. // a0001 GETQUOTAROOT INBOX
  2632. // * QUOTAROOT INBOX user/sample
  2633. // * QUOTA user/sample (STORAGE 654 9765)
  2634. // a0001 OK Completed
  2635. list($code, $response) = $this->execute('GETQUOTAROOT', array($this->escape($mailbox)));
  2636. $result = false;
  2637. $min_free = PHP_INT_MAX;
  2638. $all = array();
  2639. if ($code == self::ERROR_OK) {
  2640. foreach (explode("\n", $response) as $line) {
  2641. if (preg_match('/^\* QUOTA /', $line)) {
  2642. list(, , $quota_root) = $this->tokenizeResponse($line, 3);
  2643. while ($line) {
  2644. list($type, $used, $total) = $this->tokenizeResponse($line, 1);
  2645. $type = strtolower($type);
  2646. if ($type && $total) {
  2647. $all[$quota_root][$type]['used'] = intval($used);
  2648. $all[$quota_root][$type]['total'] = intval($total);
  2649. }
  2650. }
  2651. if (empty($all[$quota_root]['storage'])) {
  2652. continue;
  2653. }
  2654. $used = $all[$quota_root]['storage']['used'];
  2655. $total = $all[$quota_root]['storage']['total'];
  2656. $free = $total - $used;
  2657. // calculate lowest available space from all storage quotas
  2658. if ($free < $min_free) {
  2659. $min_free = $free;
  2660. $result['used'] = $used;
  2661. $result['total'] = $total;
  2662. $result['percent'] = min(100, round(($used/max(1,$total))*100));
  2663. $result['free'] = 100 - $result['percent'];
  2664. }
  2665. }
  2666. }
  2667. }
  2668. if (!empty($result)) {
  2669. $result['all'] = $all;
  2670. }
  2671. return $result;
  2672. }
  2673. /**
  2674. * Send the SETACL command (RFC4314)
  2675. *
  2676. * @param string $mailbox Mailbox name
  2677. * @param string $user User name
  2678. * @param mixed $acl ACL string or array
  2679. *
  2680. * @return boolean True on success, False on failure
  2681. *
  2682. * @since 0.5-beta
  2683. */
  2684. public function setACL($mailbox, $user, $acl)
  2685. {
  2686. if (is_array($acl)) {
  2687. $acl = implode('', $acl);
  2688. }
  2689. $result = $this->execute('SETACL', array(
  2690. $this->escape($mailbox), $this->escape($user), strtolower($acl)),
  2691. self::COMMAND_NORESPONSE);
  2692. return ($result == self::ERROR_OK);
  2693. }
  2694. /**
  2695. * Send the DELETEACL command (RFC4314)
  2696. *
  2697. * @param string $mailbox Mailbox name
  2698. * @param string $user User name
  2699. *
  2700. * @return boolean True on success, False on failure
  2701. *
  2702. * @since 0.5-beta
  2703. */
  2704. public function deleteACL($mailbox, $user)
  2705. {
  2706. $result = $this->execute('DELETEACL', array(
  2707. $this->escape($mailbox), $this->escape($user)),
  2708. self::COMMAND_NORESPONSE);
  2709. return ($result == self::ERROR_OK);
  2710. }
  2711. /**
  2712. * Send the GETACL command (RFC4314)
  2713. *
  2714. * @param string $mailbox Mailbox name
  2715. *
  2716. * @return array User-rights array on success, NULL on error
  2717. * @since 0.5-beta
  2718. */
  2719. public function getACL($mailbox)
  2720. {
  2721. list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
  2722. if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
  2723. // Parse server response (remove "* ACL ")
  2724. $response = substr($response, 6);
  2725. $ret = $this->tokenizeResponse($response);
  2726. $mbox = array_shift($ret);
  2727. $size = count($ret);
  2728. // Create user-rights hash array
  2729. // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
  2730. // so we could return only standard rights defined in RFC4314,
  2731. // excluding 'c' and 'd' defined in RFC2086.
  2732. if ($size % 2 == 0) {
  2733. for ($i=0; $i<$size; $i++) {
  2734. $ret[$ret[$i]] = str_split($ret[++$i]);
  2735. unset($ret[$i-1]);
  2736. unset($ret[$i]);
  2737. }
  2738. return $ret;
  2739. }
  2740. $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
  2741. }
  2742. }
  2743. /**
  2744. * Send the LISTRIGHTS command (RFC4314)
  2745. *
  2746. * @param string $mailbox Mailbox name
  2747. * @param string $user User name
  2748. *
  2749. * @return array List of user rights
  2750. * @since 0.5-beta
  2751. */
  2752. public function listRights($mailbox, $user)
  2753. {
  2754. list($code, $response) = $this->execute('LISTRIGHTS', array(
  2755. $this->escape($mailbox), $this->escape($user)));
  2756. if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
  2757. // Parse server response (remove "* LISTRIGHTS ")
  2758. $response = substr($response, 13);
  2759. $ret_mbox = $this->tokenizeResponse($response, 1);
  2760. $ret_user = $this->tokenizeResponse($response, 1);
  2761. $granted = $this->tokenizeResponse($response, 1);
  2762. $optional = trim($response);
  2763. return array(
  2764. 'granted' => str_split($granted),
  2765. 'optional' => explode(' ', $optional),
  2766. );
  2767. }
  2768. }
  2769. /**
  2770. * Send the MYRIGHTS command (RFC4314)
  2771. *
  2772. * @param string $mailbox Mailbox name
  2773. *
  2774. * @return array MYRIGHTS response on success, NULL on error
  2775. * @since 0.5-beta
  2776. */
  2777. public function myRights($mailbox)
  2778. {
  2779. list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
  2780. if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
  2781. // Parse server response (remove "* MYRIGHTS ")
  2782. $response = substr($response, 11);
  2783. $ret_mbox = $this->tokenizeResponse($response, 1);
  2784. $rights = $this->tokenizeResponse($response, 1);
  2785. return str_split($rights);
  2786. }
  2787. }
  2788. /**
  2789. * Send the SETMETADATA command (RFC5464)
  2790. *
  2791. * @param string $mailbox Mailbox name
  2792. * @param array $entries Entry-value array (use NULL value as NIL)
  2793. *
  2794. * @return boolean True on success, False on failure
  2795. * @since 0.5-beta
  2796. */
  2797. public function setMetadata($mailbox, $entries)
  2798. {
  2799. if (!is_array($entries) || empty($entries)) {
  2800. $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
  2801. return false;
  2802. }
  2803. foreach ($entries as $name => $value) {
  2804. $entries[$name] = $this->escape($name) . ' ' . $this->escape($value, true);
  2805. }
  2806. $entries = implode(' ', $entries);
  2807. $result = $this->execute('SETMETADATA', array(
  2808. $this->escape($mailbox), '(' . $entries . ')'),
  2809. self::COMMAND_NORESPONSE);
  2810. return ($result == self::ERROR_OK);
  2811. }
  2812. /**
  2813. * Send the SETMETADATA command with NIL values (RFC5464)
  2814. *
  2815. * @param string $mailbox Mailbox name
  2816. * @param array $entries Entry names array
  2817. *
  2818. * @return boolean True on success, False on failure
  2819. *
  2820. * @since 0.5-beta
  2821. */
  2822. public function deleteMetadata($mailbox, $entries)
  2823. {
  2824. if (!is_array($entries) && !empty($entries)) {
  2825. $entries = explode(' ', $entries);
  2826. }
  2827. if (empty($entries)) {
  2828. $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
  2829. return false;
  2830. }
  2831. foreach ($entries as $entry) {
  2832. $data[$entry] = null;
  2833. }
  2834. return $this->setMetadata($mailbox, $data);
  2835. }
  2836. /**
  2837. * Send the GETMETADATA command (RFC5464)
  2838. *
  2839. * @param string $mailbox Mailbox name
  2840. * @param array $entries Entries
  2841. * @param array $options Command options (with MAXSIZE and DEPTH keys)
  2842. *
  2843. * @return array GETMETADATA result on success, NULL on error
  2844. *
  2845. * @since 0.5-beta
  2846. */
  2847. public function getMetadata($mailbox, $entries, $options=array())
  2848. {
  2849. if (!is_array($entries)) {
  2850. $entries = array($entries);
  2851. }
  2852. // create entries string
  2853. foreach ($entries as $idx => $name) {
  2854. $entries[$idx] = $this->escape($name);
  2855. }
  2856. $optlist = '';
  2857. $entlist = '(' . implode(' ', $entries) . ')';
  2858. // create options string
  2859. if (is_array($options)) {
  2860. $options = array_change_key_case($options, CASE_UPPER);
  2861. $opts = array();
  2862. if (!empty($options['MAXSIZE'])) {
  2863. $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
  2864. }
  2865. if (!empty($options['DEPTH'])) {
  2866. $opts[] = 'DEPTH '.intval($options['DEPTH']);
  2867. }
  2868. if ($opts) {
  2869. $optlist = '(' . implode(' ', $opts) . ')';
  2870. }
  2871. }
  2872. $optlist .= ($optlist ? ' ' : '') . $entlist;
  2873. list($code, $response) = $this->execute('GETMETADATA', array(
  2874. $this->escape($mailbox), $optlist));
  2875. if ($code == self::ERROR_OK) {
  2876. $result = array();
  2877. $data = $this->tokenizeResponse($response);
  2878. // The METADATA response can contain multiple entries in a single
  2879. // response or multiple responses for each entry or group of entries
  2880. if (!empty($data) && ($size = count($data))) {
  2881. for ($i=0; $i<$size; $i++) {
  2882. if (isset($mbox) && is_array($data[$i])) {
  2883. $size_sub = count($data[$i]);
  2884. for ($x=0; $x<$size_sub; $x+=2) {
  2885. if ($data[$i][$x+1] !== null)
  2886. $result[$mbox][$data[$i][$x]] = $data[$i][$x+1];
  2887. }
  2888. unset($data[$i]);
  2889. }
  2890. else if ($data[$i] == '*') {
  2891. if ($data[$i+1] == 'METADATA') {
  2892. $mbox = $data[$i+2];
  2893. unset($data[$i]); // "*"
  2894. unset($data[++$i]); // "METADATA"
  2895. unset($data[++$i]); // Mailbox
  2896. }
  2897. // get rid of other untagged responses
  2898. else {
  2899. unset($mbox);
  2900. unset($data[$i]);
  2901. }
  2902. }
  2903. else if (isset($mbox)) {
  2904. if ($data[++$i] !== null)
  2905. $result[$mbox][$data[$i-1]] = $data[$i];
  2906. unset($data[$i]);
  2907. unset($data[$i-1]);
  2908. }
  2909. else {
  2910. unset($data[$i]);
  2911. }
  2912. }
  2913. }
  2914. return $result;
  2915. }
  2916. }
  2917. /**
  2918. * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
  2919. *
  2920. * @param string $mailbox Mailbox name
  2921. * @param array $data Data array where each item is an array with
  2922. * three elements: entry name, attribute name, value
  2923. *
  2924. * @return boolean True on success, False on failure
  2925. * @since 0.5-beta
  2926. */
  2927. public function setAnnotation($mailbox, $data)
  2928. {
  2929. if (!is_array($data) || empty($data)) {
  2930. $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
  2931. return false;
  2932. }
  2933. foreach ($data as $entry) {
  2934. // ANNOTATEMORE drafts before version 08 require quoted parameters
  2935. $entries[] = sprintf('%s (%s %s)', $this->escape($entry[0], true),
  2936. $this->escape($entry[1], true), $this->escape($entry[2], true));
  2937. }
  2938. $entries = implode(' ', $entries);
  2939. $result = $this->execute('SETANNOTATION', array(
  2940. $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
  2941. return ($result == self::ERROR_OK);
  2942. }
  2943. /**
  2944. * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
  2945. *
  2946. * @param string $mailbox Mailbox name
  2947. * @param array $data Data array where each item is an array with
  2948. * two elements: entry name and attribute name
  2949. *
  2950. * @return boolean True on success, False on failure
  2951. *
  2952. * @since 0.5-beta
  2953. */
  2954. public function deleteAnnotation($mailbox, $data)
  2955. {
  2956. if (!is_array($data) || empty($data)) {
  2957. $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
  2958. return false;
  2959. }
  2960. return $this->setAnnotation($mailbox, $data);
  2961. }
  2962. /**
  2963. * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
  2964. *
  2965. * @param string $mailbox Mailbox name
  2966. * @param array $entries Entries names
  2967. * @param array $attribs Attribs names
  2968. *
  2969. * @return array Annotations result on success, NULL on error
  2970. *
  2971. * @since 0.5-beta
  2972. */
  2973. public function getAnnotation($mailbox, $entries, $attribs)
  2974. {
  2975. if (!is_array($entries)) {
  2976. $entries = array($entries);
  2977. }
  2978. // create entries string
  2979. // ANNOTATEMORE drafts before version 08 require quoted parameters
  2980. foreach ($entries as $idx => $name) {
  2981. $entries[$idx] = $this->escape($name, true);
  2982. }
  2983. $entries = '(' . implode(' ', $entries) . ')';
  2984. if (!is_array($attribs)) {
  2985. $attribs = array($attribs);
  2986. }
  2987. // create attributes string
  2988. foreach ($attribs as $idx => $name) {
  2989. $attribs[$idx] = $this->escape($name, true);
  2990. }
  2991. $attribs = '(' . implode(' ', $attribs) . ')';
  2992. list($code, $response) = $this->execute('GETANNOTATION', array(
  2993. $this->escape($mailbox), $entries, $attribs));
  2994. if ($code == self::ERROR_OK) {
  2995. $result = array();
  2996. $data = $this->tokenizeResponse($response);
  2997. // Here we returns only data compatible with METADATA result format
  2998. if (!empty($data) && ($size = count($data))) {
  2999. for ($i=0; $i<$size; $i++) {
  3000. $entry = $data[$i];
  3001. if (isset($mbox) && is_array($entry)) {
  3002. $attribs = $entry;
  3003. $entry = $last_entry;
  3004. }
  3005. else if ($entry == '*') {
  3006. if ($data[$i+1] == 'ANNOTATION') {
  3007. $mbox = $data[$i+2];
  3008. unset($data[$i]); // "*"
  3009. unset($data[++$i]); // "ANNOTATION"
  3010. unset($data[++$i]); // Mailbox
  3011. }
  3012. // get rid of other untagged responses
  3013. else {
  3014. unset($mbox);
  3015. unset($data[$i]);
  3016. }
  3017. continue;
  3018. }
  3019. else if (isset($mbox)) {
  3020. $attribs = $data[++$i];
  3021. }
  3022. else {
  3023. unset($data[$i]);
  3024. continue;
  3025. }
  3026. if (!empty($attribs)) {
  3027. for ($x=0, $len=count($attribs); $x<$len;) {
  3028. $attr = $attribs[$x++];
  3029. $value = $attribs[$x++];
  3030. if ($attr == 'value.priv' && $value !== null) {
  3031. $result[$mbox]['/private' . $entry] = $value;
  3032. }
  3033. else if ($attr == 'value.shared' && $value !== null) {
  3034. $result[$mbox]['/shared' . $entry] = $value;
  3035. }
  3036. }
  3037. }
  3038. $last_entry = $entry;
  3039. unset($data[$i]);
  3040. }
  3041. }
  3042. return $result;
  3043. }
  3044. }
  3045. /**
  3046. * Returns BODYSTRUCTURE for the specified message.
  3047. *
  3048. * @param string $mailbox Folder name
  3049. * @param int $id Message sequence number or UID
  3050. * @param bool $is_uid True if $id is an UID
  3051. *
  3052. * @return array/bool Body structure array or False on error.
  3053. * @since 0.6
  3054. */
  3055. public function getStructure($mailbox, $id, $is_uid = false)
  3056. {
  3057. $result = $this->fetch($mailbox, $id, $is_uid, array('BODYSTRUCTURE'));
  3058. if (is_array($result)) {
  3059. $result = array_shift($result);
  3060. return $result->bodystructure;
  3061. }
  3062. return false;
  3063. }
  3064. /**
  3065. * Returns data of a message part according to specified structure.
  3066. *
  3067. * @param array $structure Message structure (getStructure() result)
  3068. * @param string $part Message part identifier
  3069. *
  3070. * @return array Part data as hash array (type, encoding, charset, size)
  3071. */
  3072. public static function getStructurePartData($structure, $part)
  3073. {
  3074. $part_a = self::getStructurePartArray($structure, $part);
  3075. $data = array();
  3076. if (empty($part_a)) {
  3077. return $data;
  3078. }
  3079. // content-type
  3080. if (is_array($part_a[0])) {
  3081. $data['type'] = 'multipart';
  3082. }
  3083. else {
  3084. $data['type'] = strtolower($part_a[0]);
  3085. // encoding
  3086. $data['encoding'] = strtolower($part_a[5]);
  3087. // charset
  3088. if (is_array($part_a[2])) {
  3089. while (list($key, $val) = each($part_a[2])) {
  3090. if (strcasecmp($val, 'charset') == 0) {
  3091. $data['charset'] = $part_a[2][$key+1];
  3092. break;
  3093. }
  3094. }
  3095. }
  3096. }
  3097. // size
  3098. $data['size'] = intval($part_a[6]);
  3099. return $data;
  3100. }
  3101. public static function getStructurePartArray($a, $part)
  3102. {
  3103. if (!is_array($a)) {
  3104. return false;
  3105. }
  3106. if (empty($part)) {
  3107. return $a;
  3108. }
  3109. $ctype = is_string($a[0]) && is_string($a[1]) ? $a[0] . '/' . $a[1] : '';
  3110. if (strcasecmp($ctype, 'message/rfc822') == 0) {
  3111. $a = $a[8];
  3112. }
  3113. if (strpos($part, '.') > 0) {
  3114. $orig_part = $part;
  3115. $pos = strpos($part, '.');
  3116. $rest = substr($orig_part, $pos+1);
  3117. $part = substr($orig_part, 0, $pos);
  3118. return self::getStructurePartArray($a[$part-1], $rest);
  3119. }
  3120. else if ($part > 0) {
  3121. return (is_array($a[$part-1])) ? $a[$part-1] : $a;
  3122. }
  3123. }
  3124. /**
  3125. * Creates next command identifier (tag)
  3126. *
  3127. * @return string Command identifier
  3128. * @since 0.5-beta
  3129. */
  3130. public function nextTag()
  3131. {
  3132. $this->cmd_num++;
  3133. $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
  3134. return $this->cmd_tag;
  3135. }
  3136. /**
  3137. * Sends IMAP command and parses result
  3138. *
  3139. * @param string $command IMAP command
  3140. * @param array $arguments Command arguments
  3141. * @param int $options Execution options
  3142. *
  3143. * @return mixed Response code or list of response code and data
  3144. * @since 0.5-beta
  3145. */
  3146. public function execute($command, $arguments=array(), $options=0)
  3147. {
  3148. $tag = $this->nextTag();
  3149. $query = $tag . ' ' . $command;
  3150. $noresp = ($options & self::COMMAND_NORESPONSE);
  3151. $response = $noresp ? null : '';
  3152. if (!empty($arguments)) {
  3153. foreach ($arguments as $arg) {
  3154. $query .= ' ' . self::r_implode($arg);
  3155. }
  3156. }
  3157. // Send command
  3158. if (!$this->putLineC($query, true, ($options & self::COMMAND_ANONYMIZED))) {
  3159. $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
  3160. return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
  3161. }
  3162. // Parse response
  3163. do {
  3164. $line = $this->readLine(4096);
  3165. if ($response !== null) {
  3166. $response .= $line;
  3167. }
  3168. }
  3169. while (!$this->startsWith($line, $tag . ' ', true, true));
  3170. $code = $this->parseResult($line, $command . ': ');
  3171. // Remove last line from response
  3172. if ($response) {
  3173. $line_len = min(strlen($response), strlen($line) + 2);
  3174. $response = substr($response, 0, -$line_len);
  3175. }
  3176. // optional CAPABILITY response
  3177. if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
  3178. && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
  3179. ) {
  3180. $this->parseCapability($matches[1], true);
  3181. }
  3182. // return last line only (without command tag, result and response code)
  3183. if ($line && ($options & self::COMMAND_LASTLINE)) {
  3184. $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
  3185. }
  3186. return $noresp ? $code : array($code, $response);
  3187. }
  3188. /**
  3189. * Splits IMAP response into string tokens
  3190. *
  3191. * @param string &$str The IMAP's server response
  3192. * @param int $num Number of tokens to return
  3193. *
  3194. * @return mixed Tokens array or string if $num=1
  3195. * @since 0.5-beta
  3196. */
  3197. public static function tokenizeResponse(&$str, $num=0)
  3198. {
  3199. $result = array();
  3200. while (!$num || count($result) < $num) {
  3201. // remove spaces from the beginning of the string
  3202. $str = ltrim($str);
  3203. switch ($str[0]) {
  3204. // String literal
  3205. case '{':
  3206. if (($epos = strpos($str, "}\r\n", 1)) == false) {
  3207. // error
  3208. }
  3209. if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
  3210. // error
  3211. }
  3212. $result[] = $bytes ? substr($str, $epos + 3, $bytes) : '';
  3213. $str = substr($str, $epos + 3 + $bytes);
  3214. break;
  3215. // Quoted string
  3216. case '"':
  3217. $len = strlen($str);
  3218. for ($pos=1; $pos<$len; $pos++) {
  3219. if ($str[$pos] == '"') {
  3220. break;
  3221. }
  3222. if ($str[$pos] == "\\") {
  3223. if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
  3224. $pos++;
  3225. }
  3226. }
  3227. }
  3228. // we need to strip slashes for a quoted string
  3229. $result[] = stripslashes(substr($str, 1, $pos - 1));
  3230. $str = substr($str, $pos + 1);
  3231. break;
  3232. // Parenthesized list
  3233. case '(':
  3234. $str = substr($str, 1);
  3235. $result[] = self::tokenizeResponse($str);
  3236. break;
  3237. case ')':
  3238. $str = substr($str, 1);
  3239. return $result;
  3240. // String atom, number, astring, NIL, *, %
  3241. default:
  3242. // empty string
  3243. if ($str === '' || $str === null) {
  3244. break 2;
  3245. }
  3246. // excluded chars: SP, CTL, ), DEL
  3247. // we do not exclude [ and ] (#1489223)
  3248. if (preg_match('/^([^\x00-\x20\x29\x7F]+)/', $str, $m)) {
  3249. $result[] = $m[1] == 'NIL' ? null : $m[1];
  3250. $str = substr($str, strlen($m[1]));
  3251. }
  3252. break;
  3253. }
  3254. }
  3255. return $num == 1 ? $result[0] : $result;
  3256. }
  3257. protected static function r_implode($element)
  3258. {
  3259. $string = '';
  3260. if (is_array($element)) {
  3261. reset($element);
  3262. foreach ($element as $value) {
  3263. $string .= ' ' . self::r_implode($value);
  3264. }
  3265. }
  3266. else {
  3267. return $element;
  3268. }
  3269. return '(' . trim($string) . ')';
  3270. }
  3271. /**
  3272. * Converts message identifiers array into sequence-set syntax
  3273. *
  3274. * @param array $messages Message identifiers
  3275. * @param bool $force Forces compression of any size
  3276. *
  3277. * @return string Compressed sequence-set
  3278. */
  3279. public static function compressMessageSet($messages, $force=false)
  3280. {
  3281. // given a comma delimited list of independent mid's,
  3282. // compresses by grouping sequences together
  3283. if (!is_array($messages)) {
  3284. // if less than 255 bytes long, let's not bother
  3285. if (!$force && strlen($messages)<255) {
  3286. return $messages;
  3287. }
  3288. // see if it's already been compressed
  3289. if (strpos($messages, ':') !== false) {
  3290. return $messages;
  3291. }
  3292. // separate, then sort
  3293. $messages = explode(',', $messages);
  3294. }
  3295. sort($messages);
  3296. $result = array();
  3297. $start = $prev = $messages[0];
  3298. foreach ($messages as $id) {
  3299. $incr = $id - $prev;
  3300. if ($incr > 1) { // found a gap
  3301. if ($start == $prev) {
  3302. $result[] = $prev; // push single id
  3303. }
  3304. else {
  3305. $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
  3306. }
  3307. $start = $id; // start of new sequence
  3308. }
  3309. $prev = $id;
  3310. }
  3311. // handle the last sequence/id
  3312. if ($start == $prev) {
  3313. $result[] = $prev;
  3314. }
  3315. else {
  3316. $result[] = $start.':'.$prev;
  3317. }
  3318. // return as comma separated string
  3319. return implode(',', $result);
  3320. }
  3321. /**
  3322. * Converts message sequence-set into array
  3323. *
  3324. * @param string $messages Message identifiers
  3325. *
  3326. * @return array List of message identifiers
  3327. */
  3328. public static function uncompressMessageSet($messages)
  3329. {
  3330. if (empty($messages)) {
  3331. return array();
  3332. }
  3333. $result = array();
  3334. $messages = explode(',', $messages);
  3335. foreach ($messages as $idx => $part) {
  3336. $items = explode(':', $part);
  3337. $max = max($items[0], $items[1]);
  3338. for ($x=$items[0]; $x<=$max; $x++) {
  3339. $result[] = (int)$x;
  3340. }
  3341. unset($messages[$idx]);
  3342. }
  3343. return $result;
  3344. }
  3345. protected function _xor($string, $string2)
  3346. {
  3347. $result = '';
  3348. $size = strlen($string);
  3349. for ($i=0; $i<$size; $i++) {
  3350. $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
  3351. }
  3352. return $result;
  3353. }
  3354. /**
  3355. * Clear internal status cache
  3356. */
  3357. protected function clear_status_cache($mailbox)
  3358. {
  3359. unset($this->data['STATUS:' . $mailbox]);
  3360. $keys = array('EXISTS', 'RECENT', 'UNSEEN', 'UID-MAP');
  3361. foreach ($keys as $key) {
  3362. unset($this->data[$key]);
  3363. }
  3364. }
  3365. /**
  3366. * Clear internal cache of the current mailbox
  3367. */
  3368. protected function clear_mailbox_cache()
  3369. {
  3370. $this->clear_status_cache($this->selected);
  3371. $keys = array('UIDNEXT', 'UIDVALIDITY', 'HIGHESTMODSEQ', 'NOMODSEQ',
  3372. 'PERMANENTFLAGS', 'QRESYNC', 'VANISHED', 'READ-WRITE');
  3373. foreach ($keys as $key) {
  3374. unset($this->data[$key]);
  3375. }
  3376. }
  3377. /**
  3378. * Converts flags array into string for inclusion in IMAP command
  3379. *
  3380. * @param array $flags Flags (see self::flags)
  3381. *
  3382. * @return string Space-separated list of flags
  3383. */
  3384. protected function flagsToStr($flags)
  3385. {
  3386. foreach ((array)$flags as $idx => $flag) {
  3387. if ($flag = $this->flags[strtoupper($flag)]) {
  3388. $flags[$idx] = $flag;
  3389. }
  3390. }
  3391. return implode(' ', (array)$flags);
  3392. }
  3393. /**
  3394. * Converts datetime string into unix timestamp
  3395. *
  3396. * @param string $date Date string
  3397. *
  3398. * @return int Unix timestamp
  3399. */
  3400. protected static function strToTime($date)
  3401. {
  3402. // Clean malformed data
  3403. $date = preg_replace(
  3404. array(
  3405. '/GMT\s*([+-][0-9]+)/', // support non-standard "GMTXXXX" literal
  3406. '/[^a-z0-9\x20\x09:+-]/i', // remove any invalid characters
  3407. '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i', // remove weekday names
  3408. ),
  3409. array(
  3410. '\\1',
  3411. '',
  3412. '',
  3413. ), $date);
  3414. $date = trim($date);
  3415. // if date parsing fails, we have a date in non-rfc format
  3416. // remove token from the end and try again
  3417. while (($ts = intval(@strtotime($date))) <= 0) {
  3418. $d = explode(' ', $date);
  3419. array_pop($d);
  3420. if (empty($d)) {
  3421. break;
  3422. }
  3423. $date = implode(' ', $d);
  3424. }
  3425. return $ts < 0 ? 0 : $ts;
  3426. }
  3427. /**
  3428. * CAPABILITY response parser
  3429. */
  3430. protected function parseCapability($str, $trusted=false)
  3431. {
  3432. $str = preg_replace('/^\* CAPABILITY /i', '', $str);
  3433. $this->capability = explode(' ', strtoupper($str));
  3434. if (!empty($this->prefs['disabled_caps'])) {
  3435. $this->capability = array_diff($this->capability, $this->prefs['disabled_caps']);
  3436. }
  3437. if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
  3438. $this->prefs['literal+'] = true;
  3439. }
  3440. if ($trusted) {
  3441. $this->capability_readed = true;
  3442. }
  3443. }
  3444. /**
  3445. * Escapes a string when it contains special characters (RFC3501)
  3446. *
  3447. * @param string $string IMAP string
  3448. * @param boolean $force_quotes Forces string quoting (for atoms)
  3449. *
  3450. * @return string String atom, quoted-string or string literal
  3451. * @todo lists
  3452. */
  3453. public static function escape($string, $force_quotes=false)
  3454. {
  3455. if ($string === null) {
  3456. return 'NIL';
  3457. }
  3458. if ($string === '') {
  3459. return '""';
  3460. }
  3461. // atom-string (only safe characters)
  3462. if (!$force_quotes && !preg_match('/[\x00-\x20\x22\x25\x28-\x2A\x5B-\x5D\x7B\x7D\x80-\xFF]/', $string)) {
  3463. return $string;
  3464. }
  3465. // quoted-string
  3466. if (!preg_match('/[\r\n\x00\x80-\xFF]/', $string)) {
  3467. return '"' . addcslashes($string, '\\"') . '"';
  3468. }
  3469. // literal-string
  3470. return sprintf("{%d}\r\n%s", strlen($string), $string);
  3471. }
  3472. /**
  3473. * Set the value of the debugging flag.
  3474. *
  3475. * @param boolean $debug New value for the debugging flag.
  3476. * @param callback $handler Logging handler function
  3477. *
  3478. * @since 0.5-stable
  3479. */
  3480. public function setDebug($debug, $handler = null)
  3481. {
  3482. $this->debug = $debug;
  3483. $this->debug_handler = $handler;
  3484. }
  3485. /**
  3486. * Write the given debug text to the current debug output handler.
  3487. *
  3488. * @param string $message Debug mesage text.
  3489. *
  3490. * @since 0.5-stable
  3491. */
  3492. protected function debug($message)
  3493. {
  3494. if (($len = strlen($message)) > self::DEBUG_LINE_LENGTH) {
  3495. $diff = $len - self::DEBUG_LINE_LENGTH;
  3496. $message = substr($message, 0, self::DEBUG_LINE_LENGTH)
  3497. . "... [truncated $diff bytes]";
  3498. }
  3499. if ($this->resourceid) {
  3500. $message = sprintf('[%s] %s', $this->resourceid, $message);
  3501. }
  3502. if ($this->debug_handler) {
  3503. call_user_func_array($this->debug_handler, array(&$this, $message));
  3504. }
  3505. else {
  3506. echo "DEBUG: $message\n";
  3507. }
  3508. }
  3509. }