Пример #1
0
 public function selectUid($email)
 {
     $sql = "select userId from {$this->table} where email='{$email}' ";
     $ret = $this->db->mysqli->query($sql);
     if ($this->db->mysqli->error) {
         log::warning($sql, "log.wf");
         return false;
     }
     log::notice($sql, "log.nf");
     return $ret;
 }
Пример #2
0
 /**
  * Registers a new injector
  * 
  * @param callable $function The function to register as an injector.
  * 
  * @return void
  */
 public static function register(callable $function)
 {
     $target = null;
     $method = null;
     if (is_string($function)) {
         if (strpos($function, '::') === false) {
             $method = $function;
         } else {
             $parts = explode('::', $function);
             $target = $parts[0];
             $method = $parts[1];
         }
     } elseif (is_array($function)) {
         $target = $function[0];
         $method = $function[1];
     }
     $has = false;
     $put = null;
     if (is_null($target) && !is_null($method)) {
         $put = $method;
         $has = in_array($method, self::$injectors);
     } elseif (!is_null($target) && !is_null($method)) {
         if (is_string($target)) {
             $put = sprintf('%s::%s', $target, $method);
             $has = in_array($put, self::$injectors);
         } else {
             $put = $function;
             foreach (self::$injectors as $v) {
                 if (is_array($v) && $v[0] == $put[0] && $v[1] == $put[1]) {
                     $has = true;
                     break;
                 }
             }
         }
     }
     if ($has) {
         log::notice('Method has already been registered as an injector.');
     }
     if (is_null($put)) {
         log::error('Error validating callback function registered status.');
     }
     self::$injectors[] = $put;
 }
Пример #3
0
/**
 * Add task for a work
 * *******************
 *
 * @param  (string) (url) Url for task
 * @param  (string) (saveAs) Save to this file name
 * @return (array)
 */
function addWgetTask($url, $saveAs)
{
    function checkPermissions($path)
    {
        return file_exists($path) && is_dir($path) && is_writable($path) ? true : false;
    }
    function checkDirectory($dir)
    {
        if (!checkPermissions($dir)) {
            mkdir($dir, 0777, true);
            chmod($dir, 0777);
            return checkPermissions($dir) ? true : false;
        }
        return true;
    }
    log::debug('(call) addWgetTask() called, $url=' . var_export($url, true) . ', $saveAs=' . var_export($saveAs, true));
    define('OriginalTaskUrl', $url);
    // Save in constant original task url
    if (empty($url)) {
        return array('result' => false, 'msg' => 'No URL');
    }
    if (defined('WGET_ONE_TIME_LIMIT') && count(getWgetTasks()) + 1 > WGET_ONE_TIME_LIMIT) {
        log::notice('Task not added, because one time tasks limit is reached');
        return array('result' => false, 'msg' => 'One time tasks limit is reached');
    }
    if (!defined('DOWNLOAD_PATH')) {
        log::error('"DOWNLOAD_PATH" not defined');
        return array('result' => false, 'msg' => '"DOWNLOAD_PATH" not defined');
    }
    if (!checkDirectory(DOWNLOAD_PATH)) {
        log::error('Directory ' . var_export(DOWNLOAD_PATH, true) . ' cannot be created');
        return array('result' => false, 'msg' => 'Cannot create directory for downloads');
    }
    // DOWNLOAD YOUTUBE VIDEO
    // Detect - if url is link to youtube video
    if (stripos($url, 'youtube.com/') !== false || stripos($url, 'youtu.be/') !== false) {
        $youtubeVideos = array();
        // http://stackoverflow.com/a/10315969/2252921
        preg_match('/^(?:https?:\\/\\/)?(?:www\\.)?(?:youtu\\.be\\/|youtube\\.com\\/(?:embed\\/|v\\/|watch\\?v=|watch\\?.+&v=))((\\w|-){11})(?:\\S+)?$/i', $url, $founded);
        define('YoutubeVideoID', @$founded[1]);
        // Set as constant YouTube video ID
        if (strlen(YoutubeVideoID) == 11) {
            $rawVideoInfo = file_get_contents('http://youtube.com/get_video_info?video_id=' . YoutubeVideoID . '&ps=default&eurl=&gl=US&hl=en');
            if ($rawVideoInfo !== false) {
                parse_str($rawVideoInfo, $videoInfo);
                //var_dump($videoInfo);
                if (isset($videoInfo['url_encoded_fmt_stream_map'])) {
                    $my_formats_array = explode(',', $videoInfo['url_encoded_fmt_stream_map']);
                    foreach ($my_formats_array as $videoItem) {
                        parse_str($videoItem, $videoItemData);
                        if (isset($videoItemData['url'])) {
                            //var_dump($videoItemData);
                            switch (@$videoItemData['quality']) {
                                case 'small':
                                    $videoItemData['quality'] = '240p';
                                    break;
                                case 'medium':
                                    $videoItemData['quality'] = '360p';
                                    break;
                                case 'large':
                                    $videoItemData['quality'] = '480p';
                                    break;
                                case 'hd720':
                                    $videoItemData['quality'] = '720p';
                                    break;
                                case 'hd1080':
                                    $videoItemData['quality'] = '1080p';
                                    break;
                            }
                            array_push($youtubeVideos, array('title' => trim(@$videoInfo['title']), 'thumbnail' => @$videoInfo['thumbnail_url'], 'url' => urldecode($videoItemData['url']), 'type' => @$videoItemData['type'], 'quality' => @$videoItemData['quality']));
                        } else {
                            log::error('Link to youtube source video file not exists ' . var_export($videoItemData, true));
                            return array('result' => false, 'msg' => 'Link to youtube source video file not exists');
                        }
                    }
                } else {
                    $errorDescription = 'Youtube answer not contains data about video files';
                    if (isset($videoInfo['reason']) && !empty($videoInfo['reason'])) {
                        $errorDescription = trim(strip_tags($videoInfo['reason'], '<a><br/>'));
                    }
                    log::error($errorDescription . ', raw=' . var_export($rawVideoInfo, true));
                    return array('result' => false, 'msg' => $errorDescription);
                }
            } else {
                log::error('Cannot call "file_get_contents()" for $url=' . var_export($url, true));
                return array('result' => false, 'msg' => 'Cannot get remote content');
            }
        }
        //var_dump($youtubeVideos);
        // If we found video links
        if (count($youtubeVideos) > 0) {
            // Get first 'mp4' video
            foreach ($youtubeVideos as $video) {
                if (isset($video['type']) && !empty($video['type'])) {
                    preg_match('~\\/(.*?)\\;~', $video['type'], $videoType);
                    if (@$videoType[1] == 'mp4') {
                        $videoToDownload = $video;
                        break;
                    }
                }
            }
            // Or take first video (by default - with highest quality)
            if (!isset($videoToDownload)) {
                $videoToDownload = $youtubeVideos[0];
            }
            preg_match('~\\/(.*?)\\;~', $videoToDownload['type'], $extension);
            switch (@$extension[1]) {
                case 'mp4':
                    $fileExtension = 'mp4';
                    break;
                case 'webm':
                    $fileExtension = 'webm';
                    break;
                case 'x-flv':
                    $fileExtension = 'flv';
                    break;
                case '3gpp':
                    $fileExtension = '3gp';
                    break;
                default:
                    $fileExtension = 'video';
            }
            $clearTitle = makeStringSafe(@$videoToDownload['title']);
            // Tadaaam :)
            $url = $videoToDownload['url'];
            if (empty($saveAs)) {
                if (empty($clearTitle)) {
                    $saveAs = 'youtube_video_id' . YoutubeVideoID . ' (' . $videoToDownload['quality'] . ').' . $fileExtension;
                } else {
                    $saveAs = $videoToDownload['title'] . ' (' . $videoToDownload['quality'] . ').' . $fileExtension;
                }
            }
        }
    }
    // DOWNLOAD VK.COM VIDEO
    // Detect - if url is link to vk.com video
    if (stripos($url, 'vk.com/video_ext.php') !== false) {
        // For test code/decode url - http://meyerweb.com/eric/tools/dencoder/
        // Get url query and parse it to $q
        $urlParts = parse_url(urldecode($url));
        parse_str($urlParts['query'], $q);
        define('VkVideoID', @$q['id']);
        // Set as constant VK video ID
        if (isset($q['oid']) && !empty($q['oid']) && is_numeric($q['oid']) && is_numeric(VkVideoID) && isset($q['hash']) && !empty($q['hash'])) {
            // Build request url
            $queryUrl = 'https://vk.com/video_ext.php?oid=' . $q['oid'] . '&id=' . $q['id'] . '&hash=' . $q['hash'];
            // Get page content
            $rawVideoInfo = file_get_contents($queryUrl);
            if ($rawVideoInfo !== false) {
                if (preg_match('/.*\\<div.*id\\=\\"video_player\\".*/im', $rawVideoInfo) !== 0) {
                    $videoData = array();
                    preg_match('/\\&amp\\;url240\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['240'] = urldecode(@$f[1]);
                    preg_match('/\\&amp\\;url360\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['360'] = urldecode(@$f[1]);
                    preg_match('/\\&amp\\;url480\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['480'] = urldecode(@$f[1]);
                    preg_match('/\\&amp\\;url720\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['720'] = urldecode(@$f[1]);
                    preg_match('/\\&amp\\;thumb\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['thumbnail'] = trim(urldecode(@$f[1]));
                    preg_match('/\\&amp\\;md_title\\=(.*?)\\&amp\\;/i', $rawVideoInfo, $f);
                    $videoData['title'] = trim(urldecode(@$f[1]));
                    // video in low quality always must exists, if parse complete without errors
                    if (isset($videoData['240']) && !empty($videoData['240'])) {
                        $videoQualityStr = '';
                        if (isset($videoData['240']) && !empty($videoData['240'])) {
                            $url = $videoData['240'];
                            $videoQualityStr = '240p';
                        }
                        if (isset($videoData['360']) && !empty($videoData['360'])) {
                            $url = $videoData['360'];
                            $videoQualityStr = '360p';
                        }
                        if (isset($videoData['480']) && !empty($videoData['480'])) {
                            $url = $videoData['480'];
                            $videoQualityStr = '480p';
                        }
                        if (isset($videoData['720']) && !empty($videoData['720'])) {
                            $url = $videoData['720'];
                            $videoQualityStr = '720p';
                        }
                        $clearTitle = makeStringSafe(@$videoData['title']);
                        if (empty($saveAs)) {
                            if (empty($clearTitle)) {
                                $saveAs = 'vk_video_id' . VkVideoID . ' (' . $videoQualityStr . ').mp4';
                            } else {
                                $saveAs = $clearTitle . ' (' . $videoQualityStr . ').mp4';
                            }
                        }
                    } else {
                        log::error('Link to video file not found');
                        return array('result' => false, 'msg' => 'Link to video file not found');
                    }
                } else {
                    log::error('Video container not found $queryUrl=' . var_export($queryUrl, true));
                    return array('result' => false, 'msg' => 'Video container not found');
                }
            } else {
                log::error('Cannot call "file_get_contents()" for $url=' . var_export($url, true));
                return array('result' => false, 'msg' => 'Cannot get remote content');
            }
        } else {
            log::error('Request error - some important query part not exists, $url=' . var_export($url, true));
            return array('result' => false, 'msg' => 'Request error - some important query part(s) not exists');
        }
    }
    // DROPBOX 'Content-Disposition' bug fix
    // Issue - <https://github.com/tarampampam/wget-gui-light/issues/17>
    if (stripos($url, 'dropboxusercontent.com/') !== false) {
        $file_name = basename($url);
        if (!empty($file_name)) {
            $saveAs = $file_name;
        }
    }
    //var_dump($videoToDownload);
    $historyAction = '';
    $saveAs = makeStringSafe($saveAs);
    if (defined('LOG_HISTORY')) {
        if (checkDirectory(dirname(LOG_HISTORY))) {
            $savedAsCmdString = !empty($saveAs) ? ' ## SavedAs: \\"' . $saveAs . '\\"' : '';
            // If string passed in '$url' and saved 'OriginalTaskUrl' not equal each other,
            //   we understand - URL was PARSED and changed. And now, for a history
            //   (tadatadaaaam =)) we must write ORIGINAL url (not parsed)
            $urlForHistory = $url !== OriginalTaskUrl ? OriginalTaskUrl : $url;
            $urlForHistoryCmd = $url !== OriginalTaskUrl ? ' && URL="' . $urlForHistory . '"' : '';
            $historyAction = ' && HISTORY="' . LOG_HISTORY . '"' . $urlForHistoryCmd . ' && if [ "$?" = "0" ]; then ' . 'echo "Success: \\"$URL\\"' . $savedAsCmdString . '" >> "$HISTORY"; ' . 'else ' . 'echo "Failed: \\"$URL\\"" >> "$HISTORY"; ' . 'fi';
        } else {
            log::error('Directory ' . var_export(dirname(LOG_HISTORY), true) . ' cannot be created');
        }
    }
    $speedLimit = defined('WGET_DOWNLOAD_LIMIT') ? '--limit-rate=' . WGET_DOWNLOAD_LIMIT . 'k ' : ' ';
    $saveAsFile = !empty($saveAs) ? '--output-document="' . DOWNLOAD_PATH . '/' . $saveAs . '" ' : ' ';
    $tmpFileName = TMP_PATH . '/wget' . rand(1, 32768) . '.log.tmp';
    $cmd = '(URL="' . $url . '"; TMPFILE="' . $tmpFileName . '"; echo > "$TMPFILE"; ' . wget . ' ' . '--progress=bar:force --output-file="$TMPFILE" ' . '--tries=0 ' . '--no-check-certificate ' . '--no-cache ' . '--user-agent="Mozilla/5.0 (X11; Linux amd64; rv:21.0) Gecko/20100101 Firefox/21.0" ' . '--directory-prefix="' . DOWNLOAD_PATH . '" ' . '--content-disposition ' . '--restrict-file-names=nocontrol ' . $speedLimit . $saveAsFile . ' ' . WGET_SECRET_FLAG . ' ' . '"$URL"' . $historyAction . '; ' . rm . ' -f "$TMPFILE") > /dev/null 2>&1 & echo $!';
    log::debug('Command to exec: ' . var_export($cmd, true));
    $task = bash($cmd, 'string');
    if (empty($task)) {
        log::error('Exec task ' . var_export($cmd, true) . ' error');
        return array('result' => false, 'msg' => 'Exec task error');
    }
    usleep(100000);
    // 1/10 sec
    preg_match("/(\\d{2,7})/i", $task, $founded);
    $parentPid = @$founded[1];
    if (!validatePid($parentPid)) {
        log::error('Parent PID ' . var_export($parentPid, true) . ' for task ' . var_export($url, true) . ' not valid');
        return array('result' => false, 'msg' => 'Parent PID not valid');
    }
    //var_dump($cmd); var_dump($task); var_dump($parentPid);
    // Wait ~1 sec until child pipe not running, check every second
    for ($i = 1; $i <= 4; $i++) {
        // Get pipe with out wget task (search by $tmpFileName)
        $taskData = getWgetTasksList($tmpFileName);
        // Get last job with current URL
        $taskPid = @$taskData[0]['pid'];
        if (validatePid($taskPid)) {
            break;
        } else {
            usleep(250000);
        }
        // 1/4 sec
    }
    if (!file_exists($tmpFileName)) {
        log::notice('Task ' . var_export($url, true) . ' already complete (probably with error)');
        return array('result' => true, 'msg' => 'Task completed too fast (probably with error)');
    }
    if (!validatePid($taskPid)) {
        log::error('Task PID ' . var_export($taskPid, true) . ' for ' . var_export($url, true) . ' not valid');
        return array('result' => false, 'msg' => 'Task PID not valid');
    }
    log::notice('Task ' . var_export($url, true) . ' added successful (pid ' . var_export($taskPid, true) . ')');
    return array('result' => true, 'pid' => (int) $taskPid, 'msg' => 'Task added successful');
}