You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_imap_generic.php 131KB

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