Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Example #1
1
 /**
  * Handles the message.
  *
  * @param Message $message 
  * @param array $params
  * @param Discord $discord 
  * @param Config $config 
  * @return void 
  */
 public static function handleMessage($message, $params, $discord, $config)
 {
     if (preg_match('/https:\\/\\/discord.gg\\/(.+)/', $params[1], $matches)) {
         $invite = $discord->acceptInvite($matches[1]);
         $message->reply("Joined server {$invite->guild->name}");
     }
 }
Example #2
0
 /**
  * @covers GitElephant\Objects\Commit\Message::toString
  */
 public function testToString()
 {
     $this->assertEquals($this->shortMsg, $this->msg->toString());
     $this->assertEquals($this->shortMsg, $this->msg->__toString());
     $this->assertEquals($this->shortMsg, (string) $this->msg);
     $this->assertEquals($this->fullMsg, $this->msg->toString(true));
 }
 /**
  * Creates a new instance of the SnsNotificationMetadata
  * object, initialized from the Message
  * 
  * @param message              $message                    message for SNS
  * @param NotificationMetadata $parentNotificationMetadata parent message if 
  *                                                         applicable otherwise 
  *                                                         null
  * 
  * @throws OffAmazonPaymentsNotifications_InvalidMessageException invalid message
  * 
  * @return void
  */
 public function __construct(Message $message, NotificationMetadata $parentNotificationMetadata = null)
 {
     $this->_timestamp = $message->getMandatoryField("Timestamp");
     $this->_topicArn = $message->getMandatoryField("TopicArn");
     $this->_messageId = $message->getMandatoryField("MessageId");
     parent::__construct($parentNotificationMetadata);
 }
Example #4
0
 /**
  * Render request
  *
  * @param array       $data
  * @param string|null $template
  * @param string|null $blockClass
  * @return $this
  */
 protected function _render(array $data = array(), $template = null, $blockClass = null)
 {
     //create block
     if ($blockClass) {
         $blockClass = '\\App\\Block' . '\\' . $blockClass;
         $block = new $blockClass($data);
     } else {
         $block = new Renderer($data);
     }
     if (!$template) {
         //set template
         $template = $this->getControllerName() . DIRECTORY_SEPARATOR . $this->getActionName() . '.phtml';
     }
     $block->setTemplate($template);
     //get action HTML
     $actionHtml = $block->toHtml();
     if (!$this->isAjax()) {
         $block = new Renderer(array('content' => $actionHtml));
         $block->setTemplate('index.phtml');
         //add system messages block
         $message = new Message();
         $message->setTemplate('index/messages.phtml');
         $block->setChild('message', $message);
         echo $block->toHtml();
     } else {
         echo $actionHtml;
     }
     return $this;
 }
Example #5
0
 public function send($template, $data, $callback)
 {
     //Nova instanca Mailgun Messagebuildera koji sluzi za pravljenje emailova
     $builder = $this->mailer->MessageBuilder();
     //Kreiramo instancu Message k. da bi mogli poslati body od email,a arg. constuctora $builder,omogucava da se metode
     //iz Message k. izvrse. Message k. ne treba importovati zato sto se nalazi u istom folderu kao i Mailer k.
     $message = new Message($builder);
     //Nastimavamo od koga je poruka sa setFromAddress(),a iz konfiguracije dohvatamo email adresu od koga se salje poruka
     $message->from($this->config->get('mail.from'));
     //Dodajemo $data na view koji smo propustili kao param. u register.php ('email/auth/registered.php'),a to su korinsicki
     //podatci,tako da su ti korisnicki podatci dostupni i šerovani na views-u i da se mogu koristiti unutar Twiga
     $this->view->appendData($data);
     //Dodajemo tijelo email-a tj. poruku sa tekstom body,uz pomoc body() m. iz Message klase,u koji propustamo $template arg.
     //koji ce onda otici na register.php i preuzeti views ('email/auth/registered.php') i uz pomoc render() metoda poslati ga
     //kao tijelo emila
     $message->body($this->view->render($template));
     //Pozivamo callback funkciju sa register.php zajedno sa $message = new Message($this->mailer); da bi mogli koristiti
     //Message metode. callback func. uzima param. $message i onda prilikom svog izvrsavanje koristi to() i subject() m.
     call_user_func($callback, $message);
     //Dohvatamo domenu od Mailguna zato sto cemo slati POST request kroz Milgun API
     $domain = $this->config->get('mail.domain');
     //Slanje email poruke (getMessage() m. je iz Mailguna i sluzi sa dohvatanje email poruke,a post() sluzi sa slanje emaila)
     //"{$domain}/messages" se odnosi na nasu domenu na Mailgun st. i messages view tj. poruke na toj st.
     $this->mailer->post("{$domain}/messages", $builder->getMessage());
 }
 /**
  * @covers ApiMessage
  */
 public function testApiMessage()
 {
     $msg = new Message(array('foo', 'bar'), array('baz'));
     $msg->inLanguage('de')->title(Title::newMainPage());
     $msg2 = new ApiMessage($msg, 'code', array('data'));
     $this->compareMessages($msg, $msg2);
     $this->assertEquals('code', $msg2->getApiCode());
     $this->assertEquals(array('data'), $msg2->getApiData());
     $msg2 = unserialize(serialize($msg2));
     $this->compareMessages($msg, $msg2);
     $this->assertEquals('code', $msg2->getApiCode());
     $this->assertEquals(array('data'), $msg2->getApiData());
     $msg = new Message(array('foo', 'bar'), array('baz'));
     $msg2 = new ApiMessage(array(array('foo', 'bar'), 'baz'), 'code', array('data'));
     $this->compareMessages($msg, $msg2);
     $this->assertEquals('code', $msg2->getApiCode());
     $this->assertEquals(array('data'), $msg2->getApiData());
     $msg = new Message('foo');
     $msg2 = new ApiMessage('foo');
     $this->compareMessages($msg, $msg2);
     $this->assertEquals('foo', $msg2->getApiCode());
     $this->assertEquals(array(), $msg2->getApiData());
     $msg2->setApiCode('code', array('data'));
     $this->assertEquals('code', $msg2->getApiCode());
     $this->assertEquals(array('data'), $msg2->getApiData());
     $msg2->setApiCode(null);
     $this->assertEquals('foo', $msg2->getApiCode());
     $this->assertEquals(array('data'), $msg2->getApiData());
     $msg2->setApiData(array('data2'));
     $this->assertEquals(array('data2'), $msg2->getApiData());
 }
Example #7
0
 /**
  * Handles the message.
  *
  * @param Message $message 
  * @param array $params
  * @param Discord $discord 
  * @param Config $config 
  * @return void 
  */
 public static function handleMessage($message, $params, $discord, $config)
 {
     $prefix = isset($params[0]) ? $params[0] : $config['prefix'];
     $config['prefix'] = $prefix;
     Config::saveConfig($config, $config['filename']);
     $message->reply("Set the prefix to `{$prefix}`");
 }
Example #8
0
 static function saveNew($from, $to, $content, $source)
 {
     $sender = Profile::staticGet('id', $from);
     if (!$sender->hasRight(Right::NEWMESSAGE)) {
         // TRANS: Client exception thrown when a user tries to send a direct message while being banned from sending them.
         throw new ClientException(_('You are banned from sending direct messages.'));
     }
     $msg = new Message();
     $msg->from_profile = $from;
     $msg->to_profile = $to;
     $msg->content = common_shorten_links($content);
     $msg->rendered = common_render_text($content);
     $msg->created = common_sql_now();
     $msg->source = $source;
     $result = $msg->insert();
     if (!$result) {
         common_log_db_error($msg, 'INSERT', __FILE__);
         // TRANS: Message given when a message could not be stored on the server.
         return _('Could not insert message.');
     }
     $orig = clone $msg;
     $msg->uri = common_local_url('showmessage', array('message' => $msg->id));
     $result = $msg->update($orig);
     if (!$result) {
         common_log_db_error($msg, 'UPDATE', __FILE__);
         // TRANS: Message given when a message could not be updated on the server.
         return _('Could not update message with new URI.');
     }
     return $msg;
 }
 public function LoadMessages()
 {
     global $conversationInfos;
     $myDBConnector = new DBConnector();
     $dbARY = $myDBConnector->infos();
     $connection = new mysqli($dbARY[0], $dbARY[1], $dbARY[2], $dbARY[3]);
     if ($connection->connect_error) {
         echo "Database bağlantı hatası";
     } else {
         mysqli_set_charset($connection, "utf8");
         $query = "SELECT * FROM messages WHERE ((From_msg='" . $conversationInfos["User1"] . "' AND To_msg='" . $conversationInfos["User2"] . "') OR (From_msg='" . $conversationInfos["User2"] . "' AND To_msg='" . $conversationInfos["User1"] . "'))";
         $results = $connection->query($query);
         $num = $results->num_rows;
         echo "<form style=\"display:none;\" id=\"offsetForm_" . $conversationInfos["other"] . "\" method=\"post\" action=\"instantmessage.php?usr1=" . $conversationInfos["User1"] . "&usr2=" . $conversationInfos["User2"] . "&monitor=" . $conversationInfos["WhoIsMonitoring"] . "\">";
         echo "<input name=\"offset\" id=\"offset_" . $conversationInfos["other"] . "\" style=\"display:none;\" type=\"text\" value=\"" . $num . "\"/>";
         echo "</form>";
         while ($curResult = $results->fetch_assoc()) {
             if ($conversationInfos["WhoIsMonitoring"] == $curResult["From_msg"]) {
                 $mode = "EvSahibi";
             } else {
                 $mode = "Deplasman";
             }
             $myMessage = new Message(array($curResult["MessageDate"], $curResult["From_msg"], $curResult["To_msg"], $curResult["Message"], $mode, $curResult["Read_msg"]));
             $myMessage->MessageToHTML();
         }
         $connection->close();
     }
 }
Example #10
0
 public function send(Message $message)
 {
     $entrypoint = $this->modx->getOption('slackify_entrypoint', null, false);
     if (!$entrypoint) {
         $this->modx->log(modX::LOG_LEVEL_ERROR, 'Entry point for Slackify not defined in system settings');
         return;
     }
     $sender = $this->modx->getOption('slackify_username', null, $this->modx->getOption('site_name', null, ''));
     if (!$sender) {
         $sender = $this->modx->getOption('site_name', null, '');
     }
     $config = ['sender' => $sender, 'channel' => $this->modx->getOption('slackify_channel', null, '#general'), 'icon' => $this->modx->getOption('slackify_icon', null, ''), 'link_names' => $this->modx->getOption('slackify_link_names', null, false), 'unfurl_links' => $this->modx->getOption('slackify_unfurl_links', null, false), 'unfurl_media' => $this->modx->getOption('slackify_unfurl_media', null, true), 'allow_markdown' => $this->modx->getOption('slackify_allow_markdown', null, true), 'markdown_in_attachments' => $this->modx->getOption('slackify_markdown_in_attachments', null, '')];
     $message->setConfig(array_merge($config, $message->getConfig()));
     $fields = ['payload' => json_encode($message)];
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $entrypoint);
     curl_setopt($ch, CURLOPT_POST, count($fields));
     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $output = curl_exec($ch);
     curl_close($ch);
     if ($output != 'ok') {
         $this->modx->log(modX::LOG_LEVEL_ERROR, 'Cannot send message to Slack, reason: "' . $output . '"');
     }
 }
Example #11
0
 /**
  * Validates a message from SNS to ensure that it was delivered by AWS
  *
  * @param Message $message The message to validate
  *
  * @throws CannotGetPublicKeyFromCertificateException If the certificate cannot be retrieved
  * @throws CertificateFromUnrecognizedSourceException If the certificate's source cannot be verified
  * @throws InvalidMessageSignatureException           If the message's signature is invalid
  */
 public function validate($message)
 {
     // Get the cert's URL and ensure it is from AWS
     $certUrl = $message->get('SigningCertURL');
     $host = parse_url($certUrl, PHP_URL_HOST);
     if ('.amazonaws.com' != substr($host, -14)) {
         throw new CertificateFromUnrecognizedSourceException($host . ' did not match .amazonaws.com');
     }
     // Get the cert itself and extract the public key
     $response = wp_remote_get($certUrl);
     if (is_wp_error($response)) {
         throw new CannotGetPublicKeyFromCertificateException('Could not retrieve certificate from ' . $certUrl);
     }
     $certificate = wp_remote_retrieve_body($response);
     $publicKey = openssl_get_publickey($certificate);
     if (!$publicKey) {
         throw new CannotGetPublicKeyFromCertificateException('Could not extract public key from ' . $certUrl);
     }
     // Verify the signature of the message
     $stringToSign = $message->getStringToSign();
     $incomingSignature = base64_decode($message->get('Signature'));
     if (!openssl_verify($stringToSign, $incomingSignature, $publicKey, OPENSSL_ALGO_SHA1)) {
         throw new InvalidMessageSignatureException('The message did not match the signature ' . "\n" . $stringToSign);
     }
 }
Example #12
0
function main()
{
    $controller = new Controller();
    $response = null;
    switch ($_POST["cmd"]) {
        case "RPC":
            $username = $_POST["user"];
            if ($username == null) {
                $username = $_SESSION['user'];
            }
            $pw = $_POST["pw"];
            $plantname = $_POST["plant"];
            $code = $_POST["code"];
            $plantid = $_POST["id"];
            $response = $controller->HandleRemoteProcedureCall($_POST["func"], $username, $pw, $plantname, $code, $plantid);
            break;
        case "ContentRequest":
            if ($controller->IsLoggedIn() != "false") {
                $response = new ContentMessage($_POST["content"], $_POST["plantid"]);
            } else {
                $func = "function() { this.showLoginDialog(); this.showMessage('Sie sind nicht eingeloggt bitte einloggen', 'error'); }";
                $response = new RemoteProcedureCall($func);
            }
            break;
        default:
            $response = new Message('error', 'unknown Command');
            break;
    }
    if ($response != null) {
        $response->send();
    } else {
        echo "Error! no response was generated";
    }
}
 public function testWidth()
 {
     $message = new Message('message example');
     $this->assertEquals('message example               ', $message->width(30)->getMessage());
     $message = new Message('пример текста');
     $this->assertEquals('пример текста                 ', $message->width(30)->getMessage());
 }
Example #14
0
function round_trip($body)
{
    $msg = new Message();
    $msg->inferred = true;
    $msg->durable = true;
    $msg->id = 10;
    $msg->correlation_id = "asdf";
    $msg->properties = array();
    $msg->properties["null"] = null;
    $msg->properties["boolean"] = true;
    $msg->properties["integer"] = 123;
    $msg->properties["double"] = 3.14159;
    $msg->properties["binary"] = new Binary("binary");
    $msg->properties["symbol"] = new Symbol("symbol");
    $msg->properties["uuid"] = new UUID("1234123412341234");
    $msg->properties["list"] = new PList(1, 2, 3, 4);
    $msg->properties["char"] = new Char(321);
    $msg->body = $body;
    assert($msg->id == 10);
    assert($msg->correlation_id == "asdf");
    $copy = new Message();
    $copy->decode($msg->encode());
    assert($copy->id == $msg->id);
    assert($copy->correlation_id == $msg->correlation_id);
    $diff = array_diff($msg->properties, $copy->properties);
    assert($copy->durable == $msg->durable);
    assert(count($diff) == 0);
    assert($copy->body == $msg->body);
}
Example #15
0
 public function actionIndex()
 {
     //未提示客户端
     $platform = 'android';
     if (isset($_GET['p'])) {
         $platform = $_GET['p'];
     }
     $message = new Message();
     $relation = new Relation();
     if (isset($_POST['Message'])) {
         $message->attributes = $_POST['Message'];
         if (!empty($message->plan)) {
             $message->type = '3';
         }
         if ($message->validate()) {
             $message->file = $this->upload($message);
             if (UserState::model()->findByPk($message->receiver)->type == 0) {
                 $message->chat('android');
             } else {
                 $message->chat('ios');
             }
         }
     }
     $this->render('index', array('message' => $message));
 }
function substitmessage($texte)
{
    preg_match_all("`\\#MESSAGE_([^\\(]+)\\(([^\\)]+)\\)`", $texte, $cut);
    $tab1 = "";
    $tab2 = "";
    for ($i = 0; $i < count($cut[1]); $i++) {
        $message = new Message();
        $message->charger($cut[2][$i]);
        $messagedesc = new Messagedesc();
        $messagedesc->charger($message->id);
        if ($cut[1][$i] == "TITRE") {
            $tab1[$i] = "#MESSAGE_" . $cut[1][$i] . "(" . $cut[2][$i] . ")";
            $tab2[$i] = $messagedesc->titre;
        } else {
            if ($cut[1][$i] == "CHAPO") {
                $tab1[$i] = "#MESSAGE_" . $cut[1][$i] . "(" . $cut[2][$i] . ")";
                $tab2[$i] = $messagedesc->chapo;
            } else {
                if ($cut[1][$i] == "DESCRIPTION") {
                    $tab1[$i] = "#MESSAGE_" . $cut[1][$i] . "(" . $cut[2][$i] . ")";
                    $tab2[$i] = $messagedesc->description;
                }
            }
        }
    }
    $texte = str_replace($tab1, $tab2, $texte);
    return $texte;
}
Example #17
0
 /**
  * This function waits for input on STDIN. Support silent input by setting $silent=true
  * However this requires bash. If bash is not available, then it will fallback to the "non-silent"
  * method.
  *
  * Credit to Troels Knak-Nielsen
  * (http://www.sitepoint.com/interactive-cli-password-prompt-in-php/) for
  * inspiring most of this code.
  *
  * @param  string $prompt
  *                        This is displayed before reading any input.
  * @param  bool   $silent
  *                        Turns off echoing of input to CLI. Useful for passwords. Only works if bash is avilable.
  * @return string
  */
 public static function promptForInput($prompt, $silent = false, $default = null, \Closure $validator = null)
 {
     if ($silent == true && !self::canInvokeBash()) {
         throw new \Exception("bash cannot be invoked from PHP. 'silent' flag cannot be used.");
     }
     if (!$prompt instanceof Message) {
         $prompt = new Message($prompt);
     }
     $prompt->message(sprintf("%s%s: ", $prompt->message, !is_null($default) ? " [{$default}]" : null));
     do {
         $prompt->appendNewLine(false)->display();
         if ($silent) {
             $command = "/usr/bin/env bash -c 'read -s in && echo \$in'";
             $input = shell_exec($command);
             echo PHP_EOL;
         } else {
             $input = fgets(STDIN, 256);
         }
         $input = trim($input);
         if (strlen(trim($input)) == 0 && !is_null($default)) {
             $input = $default;
         }
     } while ($validator instanceof \Closure && !$validator($input));
     return $input;
 }
Example #18
0
 /**
  * mergeArrayWithFooter()
  * like the default merge array but add the footer accordingly.
  * It requires in the fields values: idcontact, firstname and lastname of the receiver
  * Merge an Array with a currently loaded email template
  * @param array $fields_values fields in format $fields['fieldname']=value;
  */
 function mergeArrayWithFooter($fields_values)
 {
     $bodytext = $this->getTemplateBodyText();
     $bodyhtml = $this->getTemplateBodyHtml();
     $msg = new Message();
     $unsubscribe_url = $GLOBALS['cfg_ofuz_site_http_base'] . 'unsub/' . $fields_values['idcontact'] . '/' . $_SESSION['do_User']->iduser;
     $fields_values['unsubscribe_url'] = $unsubscribe_url;
     $fields_values['sender_name'] = $_SESSION['do_User']->getFullName();
     $fields_values['receiver_name'] = $fields_values['firstname'] . " " . $fields_values['lastname'];
     if ($fields_values["flag"]) {
         if ($fields_values["flag"] == "unsubscribe_autoresponder") {
             //$unsubsribe_auto_responder = $this->getUnsubscribeAutoResponderLink($fields_values);
             //$bodytext .= $unsubsribe_auto_responder;
             //$bodyhtml .= $unsubsribe_auto_responder;
             $bodyhtml .= $this->getUnsubscribeAutoResponderLinkHTML($fields_values);
             $bodytext .= $this->getUnsubscribeAutoResponderLinkText($fields_values);
         }
     }
     $bodytext .= $msg->getMessage("email footer text");
     $bodyhtml .= $msg->getMessage("email footer html");
     $this->setBodyText(MergeString::withArray($bodytext, $fields_values));
     if (strlen($this->getTemplateBodyHtml()) > 5) {
         $this->setBodyHtml(MergeString::withArray($bodyhtml, $fields_values));
     }
     $this->setSubject(MergeString::withArray($this->getTemplateSubject(), $fields_values));
 }
Example #19
0
 public function send($template, $data, $callback)
 {
     $message = new Message($this->mailer);
     $message->body($this->load->view($template, $data, true));
     call_user_func($callback, $message);
     return $this->mailer->send();
 }
function DajArhiviraneVrijednosti($widgetType, $widgetID)
{
    // $widgetType je atribut "type" tabele "widget", a ima vrijednosti: bool, decimal, enumerated_decimal, integer, enumerated_integer, textual, enumerated_textual
    // $widgetID je atribut "id" tabela kao što su "decimal_widget", "enumerated_decimal_widget"...
    $messages = array();
    try {
        if (strpos($widgetType, 'enumerated') == false) {
            // Provjerava da li se u stringu $widgetType nalazi string "enumerated"
            $q = mysql_query("SELECT value, date, time FROM archived_" . $widgetType . "_value WHERE " . $widgetType . "_widget_id = '" . $widgetID . "';") or die("Error in query: " . mysql_error());
        } else {
            $type = substr($widgetType, 11);
            // Odstranjuje "enumerated" iz stringa $widgetType. Pogledati nazive tabela u bazi radi boljeg razumijevanja.
            $q = mysql_query("SELECT value, date, time FROM archived_" . $type . "_value WHERE enumerated_" . $type . "_widget_id = '" . $widgetID . "';") or die("Error in query: " . mysql_error());
        }
        while ($row = mysql_fetch_assoc($q)) {
            $message = new Message();
            $message->setValue($row['value']);
            $message->setDate($row['date']);
            $message->setTime($row['time']);
            array_push($messages, $message);
        }
        return $messages;
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n";
    }
}
Example #21
0
 /**
  * Handles the message.
  *
  * @param Message $message 
  * @param array $params
  * @param Discord $discord 
  * @param Config $config 
  * @param Bot $bot 
  * @return void 
  */
 public static function handleMessage($message, $params, $discord, $config, $bot)
 {
     if (!isset($params[0])) {
         $message->reply('Please pass through a guild name.');
         return;
     }
     $guild = implode(' ', $params);
     $guild = $discord->guilds->get('name', $guild);
     if (is_null($guild)) {
         $message->reply('Could not find the guild!');
         return;
     }
     foreach ($guild->channels as $channel) {
         try {
             $invite = $channel->createInvite();
         } catch (DiscordRequestFailedException $e) {
             echo "Error attempting to create invite: {$e->getMessage()}\r\n";
             continue;
         }
         $message->author->sendMessage("Invite: {$invite->invite_url}");
         $message->reply('Invite sent in PM.');
         return;
     }
     $message->reply('Was unable to create an invite for "' . $guild->name . '"');
 }
 /**
  * Transforms an object into an elastica object
  *
  * @param \Message $message the object to convert
  * @param array    $fields  the keys we want to have in the returned array
  *
  * @return Document
  **/
 public function transform($message, array $fields = array())
 {
     $data = array('content' => $message->getContent());
     $document = new Document($message->getId(), $data);
     $document->setParent($message->getGroup()->getId());
     return $document;
 }
 /**
  * @since 2.4
  *
  * @param string $msgKey
  */
 public function addErrorWithMsgKey($msgKey)
 {
     $params = func_get_args();
     array_shift($params);
     $message = new \Message($msgKey, $params);
     $this->addError(str_replace(array('['), array('&#x005B;'), $message->inContentLanguage()->text()));
 }
function attachSelectedMessages($msg, $imapConnection)
{
    global $username, $attachment_dir, $startMessage, $data_dir, $composesession, $uid_support, $msgs, $thread_sort_messages, $allow_server_sort, $show_num, $compose_messages;
    if (!isset($compose_messages)) {
        $compose_messages = array();
        sqsession_register($compose_messages, 'compose_messages');
    }
    if (!$composesession) {
        $composesession = 1;
        sqsession_register($composesession, 'composesession');
    } else {
        $composesession++;
        sqsession_register($composesession, 'composesession');
    }
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir, $composesession);
    if ($thread_sort_messages || $allow_server_sort) {
        $start_index = 0;
    } else {
        $start_index = ($startMessage - 1) * $show_num;
    }
    $i = 0;
    $j = 0;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    $composeMessage = new Message();
    $rfc822_header = new Rfc822Header();
    $composeMessage->rfc822_header = $rfc822_header;
    $composeMessage->reply_rfc822_header = '';
    while ($j < count($msg)) {
        if (isset($msg[$i])) {
            $id = $msg[$i];
            $body_a = sqimap_run_command($imapConnection, "FETCH {$id} RFC822", true, $response, $readmessage, $uid_support);
            if ($response == 'OK') {
                // fetch the subject for the message with $id from msgs.
                // is there a more efficient way to do this?
                foreach ($msgs as $k => $vals) {
                    if ($vals['ID'] == $id) {
                        $subject = $msgs[$k]['SUBJECT'];
                        break;
                    }
                }
                array_shift($body_a);
                array_pop($body_a);
                $body = implode('', $body_a);
                $body .= "\r\n";
                $localfilename = GenerateRandomString(32, 'FILE', 7);
                $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
                $fp = fopen($full_localfilename, 'wb');
                fwrite($fp, $body);
                fclose($fp);
                $composeMessage->initAttachment('message/rfc822', $subject . '.msg', $full_localfilename);
            }
            $j++;
        }
        $i++;
    }
    $compose_messages[$composesession] = $composeMessage;
    sqsession_register($compose_messages, 'compose_messages');
    session_write_close();
    return $composesession;
}
 public function actionCompose($id = null)
 {
     $message = new Message();
     if (Yii::app()->request->getPost('Message')) {
         $receiverName = Yii::app()->request->getPost('receiver');
         $message->attributes = Yii::app()->request->getPost('Message');
         $message->sender_id = Yii::app()->user->getId();
         if ($message->save()) {
             Yii::app()->user->setFlash('messageModule', MessageModule::t('Message has been sent'));
             $this->redirect($this->createUrl('inbox/'));
         } else {
             if ($message->hasErrors('receiver_id')) {
                 $message->receiver_id = null;
                 $receiverName = '';
             }
         }
     } else {
         if ($id) {
             $receiver = call_user_func(array(call_user_func(array(Yii::app()->getModule('message')->userModel, 'model')), 'findByPk'), $id);
             if ($receiver) {
                 $receiverName = call_user_func(array($receiver, Yii::app()->getModule('message')->getNameMethod));
                 $message->receiver_id = $receiver->id;
             }
         }
     }
     $this->render(Yii::app()->getModule('message')->viewPath . '/compose', array('model' => $message, 'receiverName' => isset($receiverName) ? $receiverName : null));
 }
 /**
  * 
  * @param Message $message_
  * @param array $arrayFilter
  * @throws InvalidArgumentException
  */
 public function insertMessage(Message $message_, array $arrayFilter = array())
 {
     try {
         if (is_null($this->table)) {
             throw new InvalidArgumentException('Attribute "table" can\'t be NULL !');
         }
         $userMapper = new UserMapper();
         $userMapper->setId($message_->getIdSender());
         $user_sender = $userMapper->selectUser();
         $userMapper->setId($message_->getIdReceiver());
         $user_receiver = $userMapper->selectUser();
         if (!is_null($user_sender->getId()) && !is_null($user_receiver->getId())) {
             return parent::insert($this->table, $message_, $arrayFilter);
         } elseif (is_null($user_sender->getId())) {
             throw new Exception('User sender does not exist !');
         } elseif (is_null($user_receiver->getId())) {
             throw new Exception('User receiver does not exist !');
         }
     } catch (InvalidArgumentException $e) {
         print $e->getMessage();
         exit;
     } catch (Exception $e) {
         print $e->getMessage();
         exit;
     }
 }
 /**
  * Creates a new instance of the IPNNotificationMetadata
  * object, initialized from the Message
  * 
  * @param message                                             $message                    message for IPN
  * @param OffAmazonPaymentsNotifications_NotificationMetadata $parentNotificationMetadata parent message if 
  *                                                                                        applicable otherwise 
  *                                                                                        null
  * 
  * @throws OffAmazonPaymentsNotifications_InvalidMessageException invalid message
  * 
  * @return void
  */
 public function __construct(Message $message, OffAmazonPaymentsNotifications_NotificationMetadata $parentNotificationMetadata = null)
 {
     $this->_timestamp = $message->getMandatoryField("Timestamp");
     $this->_releaseEnvironment = $message->getMandatoryField("ReleaseEnvironment");
     $this->_notificationReferenceId = $message->getMandatoryField("NotificationReferenceId");
     parent::__construct($parentNotificationMetadata);
 }
Example #28
0
 public function getMessages($from = 0, $count = 2)
 {
     $total = $this->getTotalMessages();
     if ($from + $count > $total) {
         $count = $total - $from;
     }
     $headers = array();
     $fetch_query = new \Horde_Imap_Client_Fetch_Query();
     $fetch_query->envelope();
     $fetch_query->flags();
     $fetch_query->seq();
     $fetch_query->size();
     $fetch_query->uid();
     $fetch_query->imapDate();
     $headers = array_merge($headers, array('importance', 'list-post', 'x-priority'));
     $headers[] = 'content-type';
     $fetch_query->headers('imp', $headers, array('cache' => true, 'peek' => true));
     $opt = array('ids' => $from + 1 . ':' . ($from + 1 + $count));
     $opt = array();
     // $list is an array of Horde_Imap_Client_Data_Fetch objects.
     $headers = $this->conn->fetch($this->folder_id, $fetch_query, $opt);
     ob_start();
     // fix for Horde warnings
     $messages = array();
     foreach ($headers as $message_id => $header) {
         $message = new Message($this->conn, $this->folder_id, $message_id);
         $message->setInfo($header);
         $messages[] = $message->getListArray();
     }
     ob_clean();
     return $messages;
 }
Example #29
0
 /**
  * Constructor
  *
  * @param Message   $message Original message
  * @param \stdClass $responseBody Response from Curl.
  */
 public function __construct(Message $message, \stdClass $responseBody)
 {
     $this->multicastId = $responseBody->multicast_id;
     $this->success = $responseBody->success;
     $this->failure = $responseBody->failure;
     $this->canonicalIds = $responseBody->canonical_ids;
     $this->results = [];
     if ($message->getTo()) {
         $sentIds = [$message->getTo()];
     } else {
         $sentIds = $message->getRegistrationIds();
     }
     foreach ($responseBody->results as $k => $v) {
         $id = $sentIds[$k];
         //Convert from stdClass to assoc array
         $array = get_object_vars($v);
         $this->results[$id] = $array;
         //New Registration IDs
         if (isset($array['registration_id'])) {
             $this->newRegistrationIds[$id] = $array['registration_id'];
         }
         //Failures
         if (isset($array['error'])) {
             $this->failedIds[$array['error']][$id] = $array;
         }
     }
 }
Example #30
0
 /**
  * Edycja komunikatu
  *
  */
 public function editAction()
 {
     $request = $this->getRequest();
     $id = $request->getParam('id');
     $id = $this->_helper->IdConvert->hexToStr($id);
     $logic = new Logic_Message();
     //$form = $logic->getFormGeneric();
     $form = new Logic_Message_Form_Generic();
     if ($request->isPost()) {
         if ($form->isCancelled($this->getRequest()->getPost())) {
             $this->_helper->redirector('index', null, null);
             return;
         }
         if ($form->isValid($request->getPost())) {
             try {
                 $logic->updateMessage($form, $id);
                 $this->cache->remove('global_messenger_cache_id');
                 $this->_helper->messenger("success", 'Message was successfully edited.');
                 $this->_helper->redirector('index');
                 return;
             } catch (Logic_Komunikat_Exception $e) {
                 $this->_helper->messenger('error', MSG_ERROR, $e);
             }
         }
     } else {
         $model = new Message();
         $data = $model->findOne($id);
         $form->setDefaults($data->toArray());
     }
     $this->view->form = $form;
 }