Copy of rcube_imap::search_index()
978161
protected function search_index()
    {
        $criteria = $this->search;
        $charset  = $this->charset;
        $imap     = $this->worker->get_imap();

        if (!$imap->connected()) {
            trigger_error("No IMAP connection for $this->folder", E_USER_WARNING);

            if ($this->threading) {
                return new rcube_result_thread($this->folder);
            }
            else {
                return new rcube_result_index($this->folder);
            }
        }

        if ($this->worker->options['skip_deleted'] && !preg_match('/UNDELETED/', $criteria)) {
            $criteria = 'UNDELETED '.$criteria;
        }

        // unset CHARSET if criteria string is ASCII, this way
        // SEARCH won't be re-sent after "unsupported charset" response
        if ($charset && $charset != 'US-ASCII' && is_ascii($criteria)) {
            $charset = 'US-ASCII';
        }

        if ($this->threading) {
            $threads = $imap->thread($this->folder, $this->threading, $criteria, true, $charset);

            // Error, try with US-ASCII (RFC5256: SORT/THREAD must support US-ASCII and UTF-8,
            // but I've seen that Courier doesn't support UTF-8)
            if ($threads->is_error() && $charset && $charset != 'US-ASCII') {
                $threads = $imap->thread($this->folder, $this->threading,
                    rcube_imap::convert_criteria($criteria, $charset), true, 'US-ASCII');
            }

            return $threads;
        }

        if ($this->sort_field) {
            $messages = $imap->sort($this->folder, $this->sort_field, $criteria, true, $charset);

            // Error, try with US-ASCII (RFC5256: SORT/THREAD must support US-ASCII and UTF-8,
            // but I've seen Courier with disabled UTF-8 support)
            if ($messages->is_error() && $charset && $charset != 'US-ASCII') {
                $messages = $imap->sort($this->folder, $this->sort_field,
                    rcube_imap::convert_criteria($criteria, $charset), true, 'US-ASCII');
            }
        }

        if (!$messages || $messages->is_error()) {
            $messages = $imap->search($this->folder,
                ($charset && $charset != 'US-ASCII' ? "CHARSET $charset " : '') . $criteria, true);

            // Error, try with US-ASCII (some servers may support only US-ASCII)
            if ($messages->is_error() && $charset && $charset != 'US-ASCII') {
                $messages = $imap->search($this->folder,
                    rcube_imap::convert_criteria($criteria, $charset), true);
            }
        }

        return $messages;
    }
717569
function OverWrite($file_in, $search, $replacement, $dest = Destination::DOWNLOAD, $file_out = "mpdf")
	{
		$pdf = file_get_contents($file_in);

		if (!is_array($search)) {
			$x = $search;
			$search = [$x];
		}
		if (!is_array($replacement)) {
			$x = $replacement;
			$replacement = [$x]; // mPDF 5.7.4
		}

		if (!$this->onlyCoreFonts && !$this->usingCoreFont) {
			foreach ($search as $k => $val) {
				$search[$k] = $this->writer->utf8ToUtf16BigEndian($search[$k], false);
				$search[$k] = $this->writer->escape($search[$k]);
				$replacement[$k] = $this->writer->utf8ToUtf16BigEndian($replacement[$k], false);
				$replacement[$k] = $this->writer->escape($replacement[$k]);
			}
		} else {
			foreach ($replacement as $k => $val) {
				$replacement[$k] = mb_convert_encoding($replacement[$k], $this->mb_enc, 'utf-8');
				$replacement[$k] = $this->writer->escape($replacement[$k]);
			}
		}

		// Get xref into array
		$xref = [];
		preg_match("/xref\n0 (\d+)\n(.*?)\ntrailer/s", $pdf, $m);
		$xref_objid = $m[1];
		preg_match_all('/(\d{10}) (\d{5}) (f|n)/', $m[2], $x);
		for ($i = 0; $i < count($x[0]); $i++) {
			$xref[] = [intval($x[1][$i]), $x[2][$i], $x[3][$i]];
		}

		$changes = [];
		preg_match("/<<\s*\/Type\s*\/Pages\s*\/Kids\s*\[(.*?)\]\s*\/Count/s", $pdf, $m);
		preg_match_all("/(\d+) 0 R /s", $m[1], $o);
		$objlist = $o[1];

		foreach ($objlist as $obj) {
			if ($this->compress) {
				preg_match("/" . ($obj + 1) . " 0 obj\n<<\s*\/Filter\s*\/FlateDecode\s*\/Length (\d+)>>\nstream\n(.*?)\nendstream\n/s", $pdf, $m);
			} else {
				preg_match("/" . ($obj + 1) . " 0 obj\n<<\s*\/Length (\d+)>>\nstream\n(.*?)\nendstream\n/s", $pdf, $m);
			}

			$s = $m[2];
			if (!$s) {
				continue;
			}

			$oldlen = $m[1];

			if ($this->encrypted) {
				$s = $this->protection->rc4($this->protection->objectKey($obj + 1), $s);
			}

			if ($this->compress) {
				$s = gzuncompress($s);
			}

			foreach ($search as $k => $val) {
				$s = str_replace($search[$k], $replacement[$k], $s);
			}

			if ($this->compress) {
				$s = gzcompress($s);
			}

			if ($this->encrypted) {
				$s = $this->protection->rc4($this->protection->objectKey($obj + 1), $s);
			}

			$newlen = strlen($s);

			$changes[($xref[$obj + 1][0])] = ($newlen - $oldlen) + (strlen($newlen) - strlen($oldlen));

			if ($this->compress) {
				$newstr = ($obj + 1) . " 0 obj\n<</Filter /FlateDecode /Length " . $newlen . ">>\nstream\n" . $s . "\nendstream\n";
			} else {
				$newstr = ($obj + 1) . " 0 obj\n<</Length " . $newlen . ">>\nstream\n" . $s . "\nendstream\n";
			}

			$pdf = str_replace($m[0], $newstr, $pdf);
		}

		// Update xref in PDF
		krsort($changes);
		$newxref = "xref\n0 " . $xref_objid . "\n";
		foreach ($xref as $v) {
			foreach ($changes as $ck => $cv) {
				if ($v[0] > $ck) {
					$v[0] += $cv;
				}
			}
			$newxref .= sprintf('%010d', $v[0]) . ' ' . $v[1] . ' ' . $v[2] . " \n";
		}
		$newxref .= "trailer";
		$pdf = preg_replace("/xref\n0 \d+\n.*?\ntrailer/s", $newxref, $pdf);

		// Update startxref in PDF
		preg_match("/startxref\n(\d+)\n%%EOF/s", $pdf, $m);
		$startxref = $m[1];
		$startxref += array_sum($changes);
		$pdf = preg_replace("/startxref\n(\d+)\n%%EOF/s", "startxref\n" . $startxref . "\n%%EOF", $pdf);

		// OUTPUT
		switch ($dest) {
			case Destination::INLINE:
				if (isset($_SERVER['SERVER_NAME'])) {
					// We send to a browser
					header('Content-Type: application/pdf');
					header('Content-Length: ' . strlen($pdf));
					header('Content-disposition: inline; filename=' . $file_out);
				}

				echo $pdf;

				break;

			case Destination::FILE:
				if (!$file_out) {
					$file_out = 'mpdf.pdf';
				}

				$f = fopen($file_out, 'wb');

				if (!$f) {
					throw new \Mpdf\MpdfException('Unable to create output file: ' . $file_out);
				}

				fwrite($f, $pdf, strlen($pdf));

				fclose($f);

				break;

			case Destination::STRING_RETURN:
				return $pdf;

			case Destination::DOWNLOAD: // Download file
			default:
				if (isset($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
					header('Content-Type: application/force-download');
				} else {
					header('Content-Type: application/octet-stream');
				}

				header('Content-Length: ' . strlen($pdf));
				header('Content-disposition: attachment; filename=' . $file_out);

				echo $pdf;

				break;
		}
	}
779065
private function action_save()
    {
        $mbox  = trim(rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST, true)); // UTF7-IMAP
        $user  = trim(rcube_utils::get_input_value('_user', rcube_utils::INPUT_POST));
        $acl   = trim(rcube_utils::get_input_value('_acl', rcube_utils::INPUT_POST));
        $oldid = trim(rcube_utils::get_input_value('_old', rcube_utils::INPUT_POST));

        $acl    = array_intersect(str_split($acl), $this->rights_supported());
        $users  = $oldid ? array($user) : explode(',', $user);
        $result = 0;

        foreach ($users as $user) {
            $user   = trim($user);
            $prefix = $this->rc->config->get('acl_groups') ? $this->rc->config->get('acl_group_prefix') : '';

            if ($prefix && strpos($user, $prefix) === 0) {
                $username = $user;
            }
            else if (!empty($this->specials) && in_array($user, $this->specials)) {
                $username = $this->gettext($user);
            }
            else if (!empty($user)) {
                if (!strpos($user, '@') && ($realm = $this->get_realm())) {
                    $user .= '@' . rcube_utils::idn_to_ascii(preg_replace('/^@/', '', $realm));
                }

                // Make sure it's valid email address to prevent from "disappearing folder"
                // issue in Cyrus IMAP e.g. when the acl user identifier contains spaces inside.
                if (strpos($user, '@') && !rcube_utils::check_email($user, false)) {
                    $user = null;
                }

                $username = $user;
            }

            if (!$acl || !$user || !strlen($mbox)) {
                continue;
            }

            $user     = $this->mod_login($user);
            $username = $this->mod_login($username);

            if ($user != $_SESSION['username'] && $username != $_SESSION['username']) {
                if ($this->rc->storage->set_acl($mbox, $user, $acl)) {
                    $ret = array('id' => rcube_utils::html_identifier($user),
                         'username' => $username, 'acl' => implode($acl), 'old' => $oldid);
                    $this->rc->output->command('acl_update', $ret);
                    $result++;
                }
            }
        }

        if ($result) {
            $this->rc->output->show_message($oldid ? 'acl.updatesuccess' : 'acl.createsuccess', 'confirmation');
        }
        else {
            $this->rc->output->show_message($oldid ? 'acl.updateerror' : 'acl.createerror', 'error');
        }
    }
562910
public function header_delimiter()
    {
        // use the configured delimiter for headers
        if (!empty($this->prop['mail_header_delimiter'])) {
            $delim = $this->prop['mail_header_delimiter'];
            if ($delim == "\n" || $delim == "\r\n") {
                return $delim;
            }
            else {
                rcube::raise_error(array(
                    'code' => 500, 'type' => 'php',
                    'file' => __FILE__, 'line' => __LINE__,
                    'message' => "Invalid mail_header_delimiter setting"
                ), true, false);
            }
        }

        $php_os = strtolower(substr(PHP_OS, 0, 3));

        if ($php_os == 'win')
            return "\r\n";

        if ($php_os == 'mac')
            return "\r\n";

        return "\n";
    }
275727
private function add_index_row($mailbox, $sort_field,
        $data, $mbox_data = array(), $exists = false, $modseq = null)
    {
        $data = array(
            $this->db->encode($data, true),
            $sort_field,
            (int) $this->skip_deleted,
            (int) $mbox_data['UIDVALIDITY'],
            (int) $mbox_data['UIDNEXT'],
            $modseq ? $modseq : $mbox_data['HIGHESTMODSEQ'],
        );

        $data    = implode('@', $data);
        $expires = $this->ttl ? $this->db->now($this->ttl) : 'NULL';

        if ($exists) {
            $res = $this->db->query(
                "UPDATE {$this->index_table}"
                ." SET `data` = ?, `valid` = 1, `expires` = $expires"
                ." WHERE `user_id` = ?"
                    ." AND `mailbox` = ?",
                $data, $this->userid, $mailbox);

            if ($this->db->affected_rows($res)) {
                return;
            }
        }

        $this->db->set_option('ignore_key_errors', true);

        $res = $this->db->query(
            "INSERT INTO {$this->index_table}"
            ." (`user_id`, `mailbox`, `valid`, `expires`, `data`)"
            ." VALUES (?, ?, 1, $expires, ?)",
            $this->userid, $mailbox, $data);

        // race-condition, insert failed so try update (#1489146)
        // thanks to ignore_key_errors "duplicate row" errors will be ignored
        if (!$exists && !$res && !$this->db->is_error($res)) {
            $res = $this->db->query(
                "UPDATE {$this->index_table}"
                ." SET `data` = ?, `valid` = 1, `expires` = $expires"
                ." WHERE `user_id` = ?"
                    ." AND `mailbox` = ?",
                $data, $this->userid, $mailbox);
        }

        $this->db->set_option('ignore_key_errors', false);
    }
191300
function GetCampCode($strMessageIndex) {
        if($this->posnetResponse->koiInfo == null)
            return "";

        if(array_key_exists($strMessageIndex, $this->posnetResponse->koiInfo))
            return $this->posnetResponse->koiInfo[$strMessageIndex]['code'];
        else
            return "";
    }
1174517
private static function replaceWildcard($data, $index)
    {
        $comunikPackage = Package::where('folder', 'comunik')->first();

        // check if comunik package is publish
        if(!is_null($comunikPackage) &&  $comunikPackage->active_012)
        {
            $data[$index] = str_replace("#link#", route('previewComunikEmailCampaign', ['campaign' => '#campaign#', 'historyId' => '#historyId#']), $data[$index]);
            $data[$index] = str_replace("#unsubscribe#", route('getUnsubscribeComunikContact', ['contactKey' => '#contactKey#']) , $data[$index]);
            $data[$index] = str_replace("#pixel#", url(config('pulsar.name')) . config('comunik.trackPixel'), $data[$index]);
        }

        // Message body
        if (isset($data['contactKey']))     $data[$index]   = str_replace("#contactKey#",   $data['contactKey'],                $data[$index]);     // Contact coded ID, to track (comunik)
        if (isset($data['company']))        $data[$index]   = str_replace("#company#",      $data['company'],                   $data[$index]);     // Company name (comunik)
        if (isset($data['name']))           $data[$index]   = str_replace("#name#",         $data['name'],                      $data[$index]);     // Contact name (comunik)
        if (isset($data['surname']))        $data[$index]   = str_replace("#surname#",      $data['surname'],                   $data[$index]);     // Contact surname (comunik)
        if (isset($data['birthDate']))      $data[$index]   = str_replace("#birthDate#",    $data['birthDate'],                 $data[$index]);     // birth date (comunik)
        if (isset($data['email']))          $data[$index]   = str_replace("#email#",        $data['email'],                     $data[$index]);     // Contact email (comunik)
        if (isset($data['campaign']))       $data[$index]   = str_replace("#campaign#",     $data['campaign'],                  $data[$index]);     // Campaign coded ID, to track (comunik)
        if (isset($data['historyId']))      $data[$index]   = str_replace("#historyId#",    $data['historyId'],                 $data[$index]);     // Sending coded ID, to track (comunik)
        $data[$index]                                       = str_replace("#date#",         date(config('pulsar.datePattern')), $data[$index]);     // Current date

        // function designed to replace the word #subject# in the title of HTML templates
        if (isset($data['subject'])) $data[$index] = str_replace("#subject#", $data['subject'], $data[$index]);

        return $data;
    }
518122
protected function _searchCode(&$tmp)
    {
        // initialise the array
        $tmp = array();

        // regexp to separate the tags from the texts
        $reg = '/(<[^>]+>)|([^<]+)+/isU';

        // last match found
        $str = '';
        $offset = 0;

        // As it finds a match
        while (preg_match($reg, $this->_html, $parse, PREG_OFFSET_CAPTURE, $offset)) {
            // if it is a tag
            if ($parse[1][0]) {
                // save the previous text if it exists
                if ($str!=='')    $tmp[] = array('txt', $str);

                // save the tag, with the offset
                $tmp[] = array('code', trim($parse[1][0]), $offset);

                // init the current text
                $str = '';
            } else { // else (if it is a text)
                // add the new text to the current text
                $str.= $parse[2][0];
            }

            // Update offset to the end of the match
            $offset = $parse[0][1] + strlen($parse[0][0]);
            unset($parse);
        }
        // if a text is present in the end, we save it
        if ($str!='') $tmp[] = array('txt', $str);
        unset($str);
    }
513145
protected function mergeIndexes(&$resource, $input)
    {
        $existingNames = [];

        foreach ($resource->indexes as $index) {
            $existingNames[] = $index->getName();
        }
        $mergeIndexes = 0;
        foreach ($input->indexes as $index) {
            $newIndex = Index::fromString($index);
            if (!empty($newIndex->getName()) && in_array($newIndex->getName(), $existingNames)) {
                $this->warn('The index "' . $newIndex->getName() . '" already exists in the file.');
                continue;
            }

            $resource->indexes[] = $newIndex;
            $existingNames[] = $newIndex->getName();
            $mergeIndexes++;
        }

        return $mergeIndexes;
    }
934934
function reindex($mode, $post_id, $message, $subject, $poster_id, $forum_id)
	{
		global $config, $phpbb_root_path, $phpEx;
		// Select the search method and do some additional checks to ensure it can actually be utilised
		$search_type =  basename($config['search_type']);

		if (!file_exists($phpbb_root_path . 'phpbb/search/' . $search_type . '.' . $phpEx))
		{
			trigger_error('NO_SUCH_SEARCH_MODULE', E_USER_ERROR);
		}

		require_once("{$phpbb_root_path}phpbb/search/$search_type.$phpEx");
		$search_type = "\\phpbb\\search\\" . $search_type;

		$error = false;
		$search = new $search_type($error);

		if ($error)
		{
			trigger_error($error);
		}

		$search->index($mode, $post_id, $message, $subject, $poster_id, $forum_id);
	}
246149
function skipIndex() {
		if( childType && childType.indexOf('[]') === childType.length-2 ) {
			childType = childType.substring(0, childType.length-2);
		}
	}
497331
function save_prefs($args)
    {
        $rcmail        = rcmail::get_instance();
        $dont_override = $rcmail->config->get('dont_override', array());

        if ($args['section'] == 'folders' && !in_array('archive_mbox', $dont_override)) {
            $args['prefs']['archive_type'] = rcube_utils::get_input_value('_archive_type', rcube_utils::INPUT_POST);
        }
        else if ($args['section'] == 'server' && !in_array('read_on_archive', $dont_override)) {
            $args['prefs']['read_on_archive'] = (bool) rcube_utils::get_input_value('_read_on_archive', rcube_utils::INPUT_POST);
        }

        return $args;
    }
572417
private function get_thread_data($mailbox, $mbox_data = array())
    {
        if (empty($mbox_data)) {
            $mbox_data = $this->imap->folder_data($mailbox);
        }

        if ($mbox_data['EXISTS']) {
            // get all threads (default sort order)
            return $this->imap->threads_direct($mailbox);
        }

        return new rcube_result_thread($mailbox, '* THREAD');
    }
1063327
private function _fetchWrapper($mailbox, $query, $options)
    {
        $this->login();

        $query = clone $query;

        $cache_array = $header_cache = $new_query = array();

        if (empty($options['ids'])) {
            $options['ids'] = $this->getIdsOb(Horde_Imap_Client_Ids::ALL);
        } elseif ($options['ids']->isEmpty()) {
            return new Horde_Imap_Client_Fetch_Results($this->_fetchDataClass);
        } elseif ($options['ids']->search_res &&
                  !$this->_capability('SEARCHRES')) {
            /* SEARCHRES requires server support. */
            throw new Horde_Imap_Client_Exception_NoSupportExtension('SEARCHRES');
        }

        $this->openMailbox($mailbox, Horde_Imap_Client::OPEN_AUTO);
        $mbox_ob = $this->_mailboxOb();

        if (!empty($options['nocache'])) {
            $this->_temp['fetch_nocache'] = true;
        }

        $cf = $this->_initCache(true)
            ? $this->_cacheFields()
            : array();

        if (!empty($cf)) {
            /* If using cache, we store by UID so we need to return UIDs. */
            $query->uid();
        }

        $modseq_check = !empty($options['changedsince']);
        if ($query->contains(Horde_Imap_Client::FETCH_MODSEQ)) {
            if (!$this->_capability()->isEnabled('CONDSTORE')) {
                unset($query[Horde_Imap_Client::FETCH_MODSEQ]);
            } elseif (empty($options['changedsince'])) {
                $modseq_check = true;
            }
        }

        if ($modseq_check &&
            !$mbox_ob->getStatus(Horde_Imap_Client::STATUS_HIGHESTMODSEQ)) {
            /* RFC 7162 [3.1.2.2] - trying to do a MODSEQ FETCH on a mailbox
             * that doesn't support it will return BAD. */
            throw new Horde_Imap_Client_Exception(
                Horde_Imap_Client_Translation::r("Mailbox does not support mod-sequences."),
                Horde_Imap_Client_Exception::MBOXNOMODSEQ
            );
        }

        /* Determine if caching is available and if anything in $query is
         * cacheable. */
        foreach ($cf as $k => $v) {
            if (isset($query[$k])) {
                switch ($k) {
                case Horde_Imap_Client::FETCH_ENVELOPE:
                case Horde_Imap_Client::FETCH_FLAGS:
                case Horde_Imap_Client::FETCH_IMAPDATE:
                case Horde_Imap_Client::FETCH_SIZE:
                case Horde_Imap_Client::FETCH_STRUCTURE:
                    $cache_array[$k] = $v;
                    break;

                case Horde_Imap_Client::FETCH_HEADERS:
                    $this->_temp['headers_caching'] = array();

                    foreach ($query[$k] as $key => $val) {
                        /* Only cache if directly requested.  Iterate through
                         * requests to ensure at least one can be cached. */
                        if (!empty($val['cache']) && !empty($val['peek'])) {
                            $cache_array[$k] = $v;
                            ksort($val);
                            $header_cache[$key] = hash('md5', serialize($val));
                        }
                    }
                    break;
                }
            }
        }

        $ret = new Horde_Imap_Client_Fetch_Results(
            $this->_fetchDataClass,
            $options['ids']->sequence ? Horde_Imap_Client_Fetch_Results::SEQUENCE : Horde_Imap_Client_Fetch_Results::UID
        );

        /* If nothing is cacheable, we can do a straight search. */
        if (empty($cache_array)) {
            $options['_query'] = $query;
            $this->_fetch($ret, array($options));
            return $ret;
        }

        $cs_ret = empty($options['changedsince'])
            ? null
            : clone $ret;

        /* Convert special searches to UID lists and create mapping. */
        $ids = $this->resolveIds(
            $this->_selected,
            $options['ids'],
            empty($options['exists']) ? 1 : 2
        );

        /* Add non-user settable cache fields. */
        $cache_array[Horde_Imap_Client::FETCH_DOWNGRADED] = self::CACHE_DOWNGRADED;

        /* Get the cached values. */
        $data = $this->_cache->get(
            $this->_selected,
            $ids->ids,
            array_values($cache_array),
            $mbox_ob->getStatus(Horde_Imap_Client::STATUS_UIDVALIDITY)
        );

        /* Build a list of what we still need. */
        $map = array_flip($mbox_ob->map->map);
        $sequence = $options['ids']->sequence;
        foreach ($ids as $uid) {
            $crit = clone $query;

            if ($sequence) {
                if (!isset($map[$uid])) {
                    continue;
                }
                $entry_idx = $map[$uid];
            } else {
                $entry_idx = $uid;
                unset($crit[Horde_Imap_Client::FETCH_UID]);
            }

            $entry = $ret->get($entry_idx);

            if (isset($map[$uid])) {
                $entry->setSeq($map[$uid]);
                unset($crit[Horde_Imap_Client::FETCH_SEQ]);
            }

            $entry->setUid($uid);

            foreach ($cache_array as $key => $cid) {
                switch ($key) {
                case Horde_Imap_Client::FETCH_DOWNGRADED:
                    if (!empty($data[$uid][$cid])) {
                        $entry->setDowngraded(true);
                    }
                    break;

                case Horde_Imap_Client::FETCH_ENVELOPE:
                    if (isset($data[$uid][$cid]) &&
                        ($data[$uid][$cid] instanceof Horde_Imap_Client_Data_Envelope)) {
                        $entry->setEnvelope($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;

                case Horde_Imap_Client::FETCH_FLAGS:
                    if (isset($data[$uid][$cid]) &&
                        is_array($data[$uid][$cid])) {
                        $entry->setFlags($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;

                case Horde_Imap_Client::FETCH_HEADERS:
                    foreach ($header_cache as $hkey => $hval) {
                        if (isset($data[$uid][$cid][$hval])) {
                            /* We have found a cached entry with the same
                             * MD5 sum. */
                            $entry->setHeaders($hkey, $data[$uid][$cid][$hval]);
                            $crit->remove($key, $hkey);
                        } else {
                            $this->_temp['headers_caching'][$hkey] = $hval;
                        }
                    }
                    break;

                case Horde_Imap_Client::FETCH_IMAPDATE:
                    if (isset($data[$uid][$cid]) &&
                        ($data[$uid][$cid] instanceof Horde_Imap_Client_DateTime)) {
                        $entry->setImapDate($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;

                case Horde_Imap_Client::FETCH_SIZE:
                    if (isset($data[$uid][$cid])) {
                        $entry->setSize($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;

                case Horde_Imap_Client::FETCH_STRUCTURE:
                    if (isset($data[$uid][$cid]) &&
                        ($data[$uid][$cid] instanceof Horde_Mime_Part)) {
                        $entry->setStructure($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;
                }
            }

            if (count($crit)) {
                $sig = $crit->hash();
                if (isset($new_query[$sig])) {
                    $new_query[$sig]['i'][] = $entry_idx;
                } else {
                    $new_query[$sig] = array(
                        'c' => $crit,
                        'i' => array($entry_idx)
                    );
                }
            }
        }

        $to_fetch = array();
        foreach ($new_query as $val) {
            $ids_ob = $this->getIdsOb(null, $sequence);
            $ids_ob->duplicates = true;
            $ids_ob->add($val['i']);
            $to_fetch[] = array_merge($options, array(
                '_query' => $val['c'],
                'ids' => $ids_ob
            ));
        }

        if (!empty($to_fetch)) {
            $this->_fetch(is_null($cs_ret) ? $ret : $cs_ret, $to_fetch);
        }

        if (is_null($cs_ret)) {
            return $ret;
        }

        /* If doing changedsince query, and all other data is cached, we still
         * need to hit IMAP server to determine proper results set. */
        if (empty($new_query)) {
            $squery = new Horde_Imap_Client_Search_Query();
            $squery->modseq($options['changedsince'] + 1);
            $squery->ids($options['ids']);

            $cs = $this->search($this->_selected, $squery, array(
                'sequence' => $sequence
            ));

            foreach ($cs['match'] as $val) {
                $entry = $ret->get($val);
                if ($sequence) {
                    $entry->setSeq($val);
                } else {
                    $entry->setUid($val);
                }
                $cs_ret[$val] = $entry;
            }
        } else {
            foreach ($cs_ret as $key => $val) {
                $val->merge($ret->get($key));
            }
        }

        return $cs_ret;
    }
1291167
def run(self, **kwargs):
        
        try:
            # connect to server and login
            box = imaplib.IMAP4_SSL(settings.IMAP_SERVER)
            box.login(settings.IMAP_USERNAME, settings.IMAP_PASSWORD)
            box.select()

            # search for all mails in the mailbox
            result, mail_indices = box.search(None, 'ALL')

            # if everything was ok...
            if result == 'OK':

                # check number of mails
                mail_count = len(mail_indices[0].split())
                logger.info('found %(mail_count)d mails...' % {'mail_count': mail_count})

                # iterate the mail indices and fetch the mails
                ips_created = 0
                for mail_index in mail_indices[0].split():
                    logger.info('fetching mail %(mail_index)s...' % {'mail_index': int(mail_index)})
                    # mail data is a list with a tuple
                    sub_result, mail_data = box.fetch(mail_index, '(BODY[TEXT])')
                    if sub_result == 'OK':

                        # fetch the ips
                        ips = list_remove_duplicates(
                            self.find_ips(''.join([str(data) for data in mail_data[0]]))
                        )

                        # if ips found, add them and delete the mail
                        if len(ips) > 0:
                            logger.info('found %(count)d IPs' % {'count': len(ips)})
                            ips_created += IP.batch_add_ips(ips)
                            box.store(mail_index, '+FLAGS', '\\Deleted')

                    else:
                        logger.error('fetching mail with index %(index)d failed' % {'index': mail_index})

                # finally, if ips were added, unify the IPs
                if ips_created > 0:
                    logger.info('created %(count)d IPs' % {'count': ips_created})
                    IP.unify_ips()

            else:
                logger.error('search returned not OK')

            box.close()
            box.logout()
        except:
            logger.exception('retrieving mail failed')
298686
public function processCallback($input, $index, $info = [])
    {
        // Some (Windows?) systems provide incomplete `readline_info`, so let's
        // try to work around it.
        $line = $info['line_buffer'];
        if (isset($info['end'])) {
            $line = \substr($line, 0, $info['end']);
        }
        if ($line === '' && $input !== '') {
            $line = $input;
        }

        $tokens = \token_get_all('<?php ' . $line);

        // remove whitespaces
        $tokens = \array_filter($tokens, function ($token) {
            return !AbstractMatcher::tokenIs($token, AbstractMatcher::T_WHITESPACE);
        });

        $matches = [];
        foreach ($this->matchers as $matcher) {
            if ($matcher->hasMatched($tokens)) {
                $matches = \array_merge($matcher->getMatches($tokens), $matches);
            }
        }

        $matches = \array_unique($matches);

        return !empty($matches) ? $matches : [''];
    }
497634
function tpl_key_import_form($attrib)
    {
        $attrib += array('id' => 'rcmKeyImportForm');

        $upload = new html_inputfield(array('type' => 'file', 'name' => '_file',
            'id' => 'rcmimportfile', 'size' => 30));
        $search = new html_inputfield(array('type' => 'text', 'name' => '_search',
            'id' => 'rcmimportsearch', 'size' => 30));

        $upload_button = new html_inputfield(array(
                'type'    => 'button',
                'value'   => $this->rc->gettext('import'),
                'class'   => 'button',
                'onclick' => "return rcmail.command('plugin.enigma-import','',this,event)",
        ));

        $search_button = new html_inputfield(array(
                'type'    => 'button',
                'value'   => $this->rc->gettext('search'),
                'class'   => 'button',
                'onclick' => "return rcmail.command('plugin.enigma-import-search','',this,event)",
        ));

        $upload_form = html::div(null,
            rcube::Q($this->enigma->gettext('keyimporttext'), 'show')
            . html::br() . html::br() . $upload->show()
            . html::br() . html::br() . $upload_button->show()
        );

        $search_form = html::div(null,
            rcube::Q($this->enigma->gettext('keyimportsearchtext'), 'show')
            . html::br() . html::br() . $search->show()
            . html::br() . html::br() . $search_button->show()
        );

        $form = html::tag('fieldset', '', html::tag('legend', null, $this->enigma->gettext('keyimportlabel')) . $upload_form)
            . html::tag('fieldset', '', html::tag('legend', null, $this->enigma->gettext('keyimportsearchlabel')) . $search_form);

        $this->rc->output->add_label('selectimportfile', 'importwait', 'nopubkeyfor', 'nopubkeyforsender',
            'encryptnoattachments','encryptedsendialog','searchpubkeyservers', 'importpubkeys',
            'encryptpubkeysfound',  'search', 'close', 'import', 'keyid', 'keylength', 'keyexpired',
            'keyrevoked', 'keyimportsuccess', 'keyservererror');
        $this->rc->output->add_gui_object('importform', $attrib['id']);
        $this->rc->output->include_script('publickey.js');

        $out = $this->rc->output->form_tag(array(
            'action'  => $this->rc->url(array('action' => $this->rc->action, 'a' => 'import')),
            'method'  => 'post',
            'enctype' => 'multipart/form-data') + $attrib,
            $form
        );

        return $out;
    }