actions.class.php 5.81 KB
Newer Older
Игорь's avatar
init    
Игорь committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php

/**
 *
 * @package    symfony
 * @subpackage plugin
 * @author     davert <davert@ukr.net>
 */
class bugTrackerActions extends sfActions
{
    public function executeProxy(sfWebRequest $request)
    {
        $proxy = new sfBugTrackerProxy;
        $proxy->parse($request->getGetParameters());
        return sfView::NONE;
    }

    public function executeBugReport(sfWebRequest $request)
    {
        // $param = $request->getParameterHolder()->getAll();
        $attach = $request->getFiles();
        $param = $request->getParameter('bug_report');
        $user = $this->getUser();
        $param['username'] = '';
        if($user->isAuthenticated()){
            $param['username'] = $user->getUsername();
        }
        $this->writeToLog($param);
        // echo var_export($param, true)."\n".var_export($files, true);
        if (isset($param['screenshot']) && trim($param['screenshot']) != '') {
            if (stripos($param['screenshot'], 'data:') == 0) {
                // split the string on commas
                // $data[ 0 ] == "data:image/png;base64"
                // $data[ 1 ] == <actual base64 string>
                $data = explode(',', $param['screenshot']);
                $tmpfname = tempnam(sfConfig::get('sf_cache_dir'), "screen_");
                // open the output file for writing
                $ifp = fopen($tmpfname, 'wb');
                // we could add validation here with ensuring count( $data ) > 1
                fwrite($ifp, base64_decode($data[1]));
                // clean up the file resource
                fclose($ifp);
                $info = getimagesize($tmpfname);
                $ntmpfname = $tmpfname . image_type_to_extension($info[2]);
                rename($tmpfname, $ntmpfname);
                $attach[] = $ntmpfname;
            }
        }

        sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');

        $issue_data = array('description' => get_partial('bugTracker/bug_report', $param));
        if(isset($param['msg']) && $param['msg'] != ''){
            $issue_data['subject'] = $param['msg'];
        }
        $this->redmineIssue($issue_data);

        $message = Swift_Message::newInstance();
        $setFrom = sfConfig::get('app_email_sender', 'noreply@' . $request->getHost());
        $emailTo = sfConfig::get('app_bug_tracker_email');
        $message->setFrom($setFrom)->setContentType('text/html; charset=utf-8');
        if($emailTo){
            $emailTo = explode(',', $emailTo);
        }
        $message->setSubject('Новое сообщение об ошибке в проекте «' . sfConfig::get('app_bug_tracker_project') . '»');
        try {
            $message->setBody(nl2br(get_partial('bugTracker/bug_report', $param)));
        } catch (Exception $e) {
            echo json_encode(array('status' => 'error', 'msg' => $e));
            return sfView::NONE;
        }

        if (!empty($attach)) {
            foreach ((array)$attach as $file) {
                $message->attach(Swift_Attachment::fromPath($file));
            }
        }
        if (count($emailTo) > 0) {
            $message->setTo($emailTo);
            try {
                $this->getMailer()->send($message);
            } catch (Exception $e) {
                echo json_encode(array('status' => 'error', 'msg' => $e->__toString()));
                return sfView::NONE;
            }
            echo json_encode(array('status' => 'ok'));
        } else {
            echo json_encode(array('status' => 'error', 'msg' => 'Empty emailTo'));
        }
        return sfView::NONE;
    }

    public function writeToLog($data)
    {
        $logger = new SplFileObject(sfConfig::get('sf_log_dir') . DIRECTORY_SEPARATOR . 'bug_tracker.log', 'a');
        $logger->fwrite(date('Y-m-d H:i:s') . "\n\n");
        $keys = array_keys($data);
        array_walk($keys, function (&$item) {
            $item = strlen($item);
        });
        rsort($keys, SORT_NUMERIC);
        $format = sprintf("%%-%ss: %%s\n", reset($keys));
        foreach ($data as $key => $value) {
            if ($value && is_array($value)) {
                $string = sprintf($format, $key, '');
                $logger->fwrite($string);
                $vformat = sprintf("   %%-%ss: %%s\n", reset($keys) - 3);
                foreach ($value as $vkey => $vvalue) {
                    $string = sprintf($vformat, $vkey, $vvalue);
                    $logger->fwrite($string);
                }
            } else {
                $string = sprintf($format, $key, $value);
                $logger->fwrite($string);
            }
        }
        $logger->fwrite("\n\n\n");
        unset($logger);
    }

    private function redmineIssue($data = array())
    {
        $redmine = sfConfig::get('app_bug_tracker_redmine');
        if(isset($redmine['key']) && $redmine['key'] && isset($redmine['project_id']) && $redmine['project_id'] && isset($redmine['url']) && $redmine['url']){
            $data['project_id'] = $redmine['project_id'];
            $data['tracker_id'] = '1';
            $data['status_id'] = '1';
            $data['priority_id'] = '4';
            if(!isset($data['subject'])){
                $data['subject'] = 'Новое сообщение об ошибке';
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_URL, $redmine['url'] . '/issues.json');
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_USERPWD, $redmine['key'] . ':123');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('issue' => $data)));
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_exec($ch);
            curl_close($ch);
        }
    }
}