function db_error_logger($errno, $errstr, $errfile = "", $errline = "", $errorcontext = array()){
	
		$errno = makeStringSafe($errno);
		$errstr = makeStringSafe($errstr);
		$errfile = makeStringSafe($errfile);
		$errline = makeStringSafe($errline);
		
		if($errno < E_STRICT){
	
			doQuery("INSERT INTO ".getDBPrefix()."_error_log set user_id = '".getSessionVariable("user_id")."', error_number = '".$errno."',
				message = '".$errstr."', file = '".$errfile."', line_number = '".$errline."', context = '".serialize($errorcontext)."',
				time = '".getCurrentMySQLDateTime()."'");
				
			$errorrow = mysql_fetch_assoc(doQuery("SELECT error_id FROM ".getDBPrefix()."_error_log ORDER BY error_id DESC LIMIT 1"));
			
			if(getConfigVar('error_output') == ERROR_OUTPUT_DBID || getConfigVar('error_output') == ERROR_OUTPUT_BOTH){
			
				echo "<h4 style=\"color: #FF0000;\">An error occured! If you would like to report this error, please report that your 'ERROR_ID' is '".$errorrow['error_id']."'.</h4>";
			
			}
		
		}
		
		return !(getConfigVar("error_output") == ERROR_OUTPUT_PHP || getConfigVar("error_output") == ERROR_OUTPUT_BOTH);
	
	}
function addToLog($userid, $action, $description)
{
    $userid = makeStringSafe($userid);
    $action = makeStringSafe($action);
    $description = makeStringSafe($description);
    $mysqldate = getCurrentMySQLDateTime();
    $ip = getClientIP();
    $hostname = getClientHostname();
    doQuery("INSERT INTO " . getDBPrefix() . "_log SET user_id = '" . $userid . "', action_type = '" . $action . "', action_description = '" . $description . "', date = '" . $mysqldate . "', ip = '" . $ip . "', hostname='" . $hostname . "'");
}
{
    $name = makeStringSafe($name);
    $comment = makeStringSafe($comment);
    $start = makeStringSafe($start);
    $end = makeStringSafe($end);
    $user_level = makeStringSafe($user_level);
    doQuery("INSERT INTO " . getDBPrefix() . "_blackouts SET name = '" . $name . "', comments = '" . $comment . "', start_date = '" . $start . "', end_date = '" . $end . "', user_level = '" . $user_level . "'");
}
function updateBlackout($bid, $name, $comment, $start, $end, $user_level)
{
function isEquipmentReserved($equipid, $date)
{
    $equipid = makeStringSafe($equipid);
    $date = makeStringSafe($date);
    $start_Date = new DateTime($date);
    $start_Date->modify("+3 day");
    //$interval = new DateInterval("P3D");
    //$start_Date->add($interval);
    $result = doQuery("SELECT * FROM " . getDBPrefix() . "_reservations WHERE equip_id = '" . $equipid . "' AND (mod_status = '" . RES_STATUS_CONFIRMED . "' or mod_status = '" . RES_STATUS_PENDING . "') AND (start_date BETWEEN '" . $date . "' and '" . $start_Date->format("Y-m-d") . "')");
    if (mysql_num_rows($result) > 0) {
        return true;
    } else {
        return false;
    }
}
function deleteMessage($messageid){

	$messageid = makeStringSafe($messageid);
	
	doQuery("DELETE FROM ".getDBPrefix()."_messages WHERE message_id = '".$messageid."' LIMIT 1");

}
function getReservationsByEquipIDandDate($equip, $startdate, $enddate)
{
    $equip = makeStringSafe($equip);
    $startdate = makeStringSafe($startdate);
    $enddate = makeStringSafe($enddate);
    return doQuery("SELECT * FROM " . getDBPrefix() . "_reservations WHERE\r\n\tequip_id = '" . $equip . "' AND \r\n\t(mod_status = '" . RES_STATUS_PENDING . "' OR mod_status = '" . RES_STATUS_CONFIRMED . "' OR mod_status = '" . RES_STATUS_CHECKED_OUT . "')\r\n\tAND ((start_date BETWEEN '" . $startdate . "' AND '" . $enddate . "') OR (end_date BETWEEN '" . $startdate . "' AND '" . $enddate . "'))");
}
}
function getUserByUsername($username)
{
    $username = makeStringSafe($username);
    return doQuery("SELECT * FROM " . getDBPrefix() . "_users WHERE username = '******'");
Exemple #10
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');
}
    $userid = makeStringSafe($userid);
    return doQuery("SELECT * FROM " . getDBPrefix() . "_warnings WHERE user_id = '" . $userid . "'");
}
function getWarningByID($warnid)
{