diff --git a/install/checkConfiguration.php b/install/checkConfiguration.php index b94063e5f..0fb04556d 100644 --- a/install/checkConfiguration.php +++ b/install/checkConfiguration.php @@ -1,240 +1,240 @@ post = $_POST; if (!file_exists($_POST['systemRootPath'] . "index.php")) { $obj->error = "Your system path to application ({$_POST['systemRootPath']}) is wrong"; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $mysqli = @new mysqli($_POST['databaseHost'], $_POST['databaseUser'], $_POST['databasePass'], "", $_POST['databasePort']); /* * This is the "official" OO way to do it, * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0. */ if ($mysqli->connect_error) { $obj->error = ('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); if ($_POST['createTables'] == 2) { $sql = "CREATE DATABASE IF NOT EXISTS {$_POST['databaseName']}"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error creating database: " . $mysqli->error; echo json_encode($obj); exit; } } $mysqli->select_db($_POST['databaseName']); error_log("Installation: ".__LINE__); /* $cmd = "mysql -h {$_POST['databaseHost']} -u {$_POST['databaseUser']} -p {$_POST['databasePass']} {$_POST['databaseName']} < {$_POST['systemRootPath']}install/database.sql"; exec("{$cmd} 2>&1", $output, $return_val); if ($return_val !== 0) { $obj->error = "Error on command: {$cmd}"; echo json_encode($obj); exit; } */ error_log("Installation: ".__LINE__); if ($_POST['createTables'] > 0) { error_log("Installation: ".__LINE__); // Temporary variable, used to store current query $templine = ''; $installFile = "{$_POST['systemRootPath']}install/database.sql"; if(!file_exists($installFile)){ $obj->error = "File Not found {$installFile}"; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); // Read in entire file $lines = file($installFile); if(empty($lines)){ $obj->error = "File is empty {$installFile}"; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); // Loop through each line $obj->error = ""; foreach ($lines as $line) { // Skip it if it's a comment if (substr($line, 0, 2) == '--' || $line == '') continue; // Add this line to the current segment $templine .= $line; // If it has a semicolon at the end, it's the end of the query if (substr(trim($line), -1, 1) == ';') { // Perform the query //error_log("Installation: ".$templine); if (!$mysqli->query($templine)) { error_log("Installation: SQL ERROR ".$mysqli->error); $obj->error = ('Error performing query \'' . $templine . '\': ' . $mysqli->error . '

'); } // Reset temp variable to empty $templine = ''; } } error_log("Installation: ".__LINE__); } error_log("Installation: ".__LINE__); $sql = "DELETE FROM users WHERE id = 1 "; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error deleting user: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "INSERT INTO users (id, user, email, password, created, modified, isAdmin) VALUES (1, 'admin', '" . $_POST['contactEmail'] . "', '" . md5($_POST['systemAdminPass']) . "', now(), now(), true)"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error creating admin user: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "DELETE FROM categories WHERE id = 1 "; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error deleting category: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "INSERT INTO categories (id, name, clean_name, description, created, modified) VALUES (1, 'Default', 'default','', now(), now())"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error creating category: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "DELETE FROM configurations WHERE id = 1 "; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error deleting configuration: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $encoder = 'https://encoder1.avideo.com/'; if(is_dir("{$_POST['systemRootPath']}Encoder")){ $encoder = "{$_POST['webSiteRootURL']}Encoder/"; } $sql = "INSERT INTO configurations (id, video_resolution, users_id, version, webSiteTitle, language, contactEmail, encoderURL, created, modified) " . " VALUES " . " (1, '858:480', 1,'{$installationVersion}', '{$_POST['webSiteTitle']}', '{$_POST['mainLanguage']}', '{$_POST['contactEmail']}', '{$encoder}', now(), now())"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error creating configuration: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "INSERT INTO `plugins` VALUES (NULL, 'a06505bf-3570-4b1f-977a-fd0e5cab205d', 'active', now(), now(), '', 'Gallery', 'Gallery', '1.0');"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error enabling Gallery Plugin: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $mysqli->close(); if(empty($_POST['salt'])){ $_POST['salt'] = uniqid(); } $content = "error = "Error copying the encoding progress sample files. Check whether the directory {$_POST['systemRootPath']}videos/ exists and the process have permission"; echo json_encode($obj); exit; } */ error_log("Installation: ".__LINE__); $obj->success = true; echo json_encode($obj); error_log("Installation: ".__LINE__); \ No newline at end of file diff --git a/install/database.sql b/install/database.sql index dd0bee61e..7faff6aa9 100644 --- a/install/database.sql +++ b/install/database.sql @@ -1,594 +1,595 @@ -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; -- ----------------------------------------------------- -- Table `users` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `users` ( `id` INT NOT NULL AUTO_INCREMENT, `user` VARCHAR(45) NOT NULL, `name` VARCHAR(45) NULL, `email` VARCHAR(254) NULL, `password` VARCHAR(145) NOT NULL, `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `modified` DATETIME NOT NULL, `isAdmin` TINYINT(1) NOT NULL DEFAULT 0, `status` ENUM('a', 'i') NOT NULL DEFAULT 'a', `photoURL` VARCHAR(255) NULL, `lastLogin` DATETIME NULL, `recoverPass` VARCHAR(255) NULL, `backgroundURL` VARCHAR(255) NULL, `canStream` TINYINT(1) NULL, `canUpload` TINYINT(1) NULL, `canCreateMeet` TINYINT(1) NULL, `canViewChart` TINYINT(1) NOT NULL DEFAULT 0, `about` TEXT NULL, `channelName` VARCHAR(45) NULL, `emailVerified` TINYINT(1) NOT NULL DEFAULT 0, `analyticsCode` VARCHAR(45) NULL DEFAULT NULL, `externalOptions` TEXT NULL, `first_name` VARCHAR(255) NULL DEFAULT NULL, `last_name` VARCHAR(255) NULL DEFAULT NULL, `address` VARCHAR(255) NULL DEFAULT NULL, `zip_code` VARCHAR(45) NULL DEFAULT NULL, `country` VARCHAR(100) NULL DEFAULT NULL, `region` VARCHAR(100) NULL DEFAULT NULL, `city` VARCHAR(100) NULL DEFAULT NULL, `donationLink` VARCHAR(225) NULL DEFAULT NULL, `extra_info` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `user_UNIQUE` (`user` ASC)) ENGINE = InnoDB; CREATE TABLE IF NOT EXISTS `users_blob` ( `id` INT NOT NULL AUTO_INCREMENT, `blob` LONGBLOB NULL, `users_id` INT NOT NULL, `created` DATETIME NULL, `modified` DATETIME NULL, `type` VARCHAR(45) NULL, PRIMARY KEY (`id`), INDEX `fk_users_document_image_users1_idx` (`users_id` ASC), CONSTRAINT `fk_users_document_image_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `categories` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `categories` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `clean_name` VARCHAR(45) NOT NULL, `description` TEXT NULL, `nextVideoOrder` INT(2) NOT NULL DEFAULT '0', `parentId` INT NOT NULL DEFAULT '0', `created` DATETIME NOT NULL, `modified` DATETIME NOT NULL, `iconClass` VARCHAR(45) NOT NULL DEFAULT 'fa fa-folder', `users_id` INT(11) NOT NULL DEFAULT 1, `private` TINYINT(1) NULL DEFAULT 0, `allow_download` TINYINT(1) NULL DEFAULT 1, `order` INT(11) NULL DEFAULT NULL, `suggested` TINYINT(1) NULL DEFAULT NULL, PRIMARY KEY (`id`), INDEX `fk_categories_users1_idx` (`users_id` ASC), INDEX `clean_name_INDEX2` (`clean_name` ASC), INDEX `sortcategoryOrderIndex` (`order` ASC), INDEX `category_name_idx` (`name` ASC), INDEX `categoriesindex9suggested` (`suggested` ASC), FULLTEXT INDEX `index7cname` (`name`), FULLTEXT INDEX `index8cdescr` (`description`), UNIQUE INDEX `clean_name_UNIQUE` (`clean_name` ASC), CONSTRAINT `fk_categories_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; CREATE TABLE IF NOT EXISTS `sites` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NULL DEFAULT NULL, `url` VARCHAR(255) NOT NULL, `created` DATETIME NULL DEFAULT NULL, `modified` DATETIME NULL DEFAULT NULL, `status` CHAR(1) NULL DEFAULT NULL, `secret` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `videos` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `videos` ( `id` INT NOT NULL AUTO_INCREMENT, `title` VARCHAR(190) NOT NULL, `clean_title` VARCHAR(190) NOT NULL, `description` TEXT NULL, `views_count` INT NOT NULL DEFAULT 0, `views_count_25` INT(11) NULL DEFAULT 0, `views_count_50` INT(11) NULL DEFAULT 0, `views_count_75` INT(11) NULL DEFAULT 0, `views_count_100` INT(11) NULL DEFAULT 0, `status` VARCHAR(16) NOT NULL DEFAULT 'e' , `created` DATETIME NOT NULL, `modified` DATETIME NOT NULL, `users_id` INT NOT NULL, `categories_id` INT NOT NULL, `filename` VARCHAR(255) NOT NULL, `duration` VARCHAR(15) NOT NULL, `type` ENUM('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie', 'zip') NOT NULL DEFAULT 'video', `videoDownloadedLink` VARCHAR(255) NULL, `order` INT UNSIGNED NOT NULL DEFAULT 1, `rotation` SMALLINT NULL DEFAULT 0, `zoom` FLOAT NULL DEFAULT 1, `youtubeId` VARCHAR(45) NULL, `videoLink` VARCHAR(255) NULL, `next_videos_id` INT NULL, `isSuggested` INT(1) NOT NULL DEFAULT 0, `trailer1` VARCHAR(255) NULL DEFAULT NULL, `trailer2` VARCHAR(255) NULL DEFAULT NULL, `trailer3` VARCHAR(255) NULL DEFAULT NULL, `rate` FLOAT(4,2) NULL DEFAULT NULL, `can_download` TINYINT(1) NULL DEFAULT NULL, `can_share` TINYINT(1) NULL DEFAULT NULL, `rrating` VARCHAR(45) NULL DEFAULT NULL, `externalOptions` TEXT NULL DEFAULT NULL, `only_for_paid` TINYINT(1) NULL DEFAULT NULL, `serie_playlists_id` INT(11) NULL DEFAULT NULL, `sites_id` INT(11) NULL, `video_password` VARCHAR(45) NULL DEFAULT NULL, `encoderURL` VARCHAR(255) NULL DEFAULT NULL, `filepath` VARCHAR(255) NULL DEFAULT NULL, `filesize` BIGINT(19) UNSIGNED NULL DEFAULT 0, `live_transmitions_history_id` INT(11) NULL DEFAULT NULL, `total_seconds_watching` INT(11) NULL DEFAULT 0, PRIMARY KEY (`id`), INDEX `fk_videos_users_idx` (`users_id` ASC), INDEX `fk_videos_categories1_idx` (`categories_id` ASC), UNIQUE INDEX `clean_title_UNIQUE` (`clean_title` ASC), INDEX `index5` (`order` ASC), INDEX `fk_videos_videos1_idx` (`next_videos_id` ASC), INDEX `fk_videos_sites1_idx` (`sites_id` ASC), INDEX `clean_title_INDEX` (`clean_title` ASC), INDEX `video_filename_INDEX` (`filename` ASC), INDEX `video_status_idx` (`status` ASC), INDEX `video_type_idx` (`type` ASC) , INDEX `fk_videos_live_transmitions_history1_idx` (`live_transmitions_history_id` ASC), INDEX `total_sec_watchinindex` (`total_seconds_watching` ASC), FULLTEXT INDEX `index17vname` (`title`), FULLTEXT INDEX `index18vdesc` (`description`), CONSTRAINT `fk_videos_sites1` FOREIGN KEY (`sites_id`) REFERENCES `sites` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_videos_users` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_videos_categories1` FOREIGN KEY (`categories_id`) REFERENCES `categories` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_videos_videos1` FOREIGN KEY (`next_videos_id`) REFERENCES `videos` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_videos_playlists1` FOREIGN KEY (`serie_playlists_id`) REFERENCES `playlists` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; CREATE TABLE IF NOT EXISTS `videos_metadata` ( `id` INT NOT NULL AUTO_INCREMENT, `videos_id` INT NOT NULL, `resolution` VARCHAR(12) NOT NULL, `format` VARCHAR(12) NOT NULL, `stream_id` INT NOT NULL, `name` VARCHAR(128) NOT NULL, `value` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE (`videos_id`, `resolution`, `format`, `stream_id`, `name`), INDEX `fk_videos_metadata_videos1_idx` (`videos_id` ASC), CONSTRAINT `fk_videos_metadata_videos1` FOREIGN KEY (`videos_id`) REFERENCES `videos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `comments` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `comments` ( `id` INT NOT NULL AUTO_INCREMENT, `comment` TEXT NOT NULL, `videos_id` INT NOT NULL, `users_id` INT NOT NULL, `created` DATETIME NOT NULL, `modified` DATETIME NOT NULL, `comments_id_pai` INT NULL, `pin` INT(1) NOT NULL DEFAULT 0 COMMENT 'If = 1 will be on the top', PRIMARY KEY (`id`), INDEX `fk_comments_videos1_idx` (`videos_id` ASC), INDEX `fk_comments_users1_idx` (`users_id` ASC), INDEX `fk_comments_comments1_idx` (`comments_id_pai` ASC), CONSTRAINT `fk_comments_videos1` FOREIGN KEY (`videos_id`) REFERENCES `videos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_comments_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_comments_comments1` FOREIGN KEY (`comments_id_pai`) REFERENCES `comments` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `configurations` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `configurations` ( `id` INT NOT NULL, `video_resolution` VARCHAR(12) NOT NULL, `users_id` INT NOT NULL, `version` VARCHAR(10) NOT NULL, `webSiteTitle` VARCHAR(45) NOT NULL DEFAULT 'AVideo', `language` VARCHAR(6) NOT NULL DEFAULT 'en', `contactEmail` VARCHAR(254) NOT NULL, `modified` DATETIME NOT NULL, `created` DATETIME NOT NULL, `authGoogle_id` VARCHAR(255) NULL, `authGoogle_key` VARCHAR(255) NULL, `authGoogle_enabled` TINYINT(1) NOT NULL DEFAULT 0, `authFacebook_id` VARCHAR(255) NULL, `authFacebook_key` VARCHAR(255) NULL, `authFacebook_enabled` TINYINT(1) NOT NULL DEFAULT 0, `authCanUploadVideos` TINYINT(1) NOT NULL DEFAULT 0, `authCanViewChart` TINYINT(2) NOT NULL DEFAULT 0, `authCanComment` TINYINT(1) NOT NULL DEFAULT 1, `head` TEXT NULL, `logo` VARCHAR(255) NULL, `logo_small` VARCHAR(255) NULL, `adsense` TEXT NULL, `mode` ENUM('Youtube', 'Gallery') NULL DEFAULT 'Youtube', `disable_analytics` TINYINT(1) NULL DEFAULT 0, `disable_youtubeupload` TINYINT(1) NULL DEFAULT 0, `allow_download` TINYINT(1) NULL DEFAULT 0, `session_timeout` INT NULL DEFAULT 3600, `autoplay` TINYINT(1) NULL, `theme` VARCHAR(45) NULL DEFAULT 'default', `smtp` TINYINT(1) NULL, `smtpAuth` TINYINT(1) NULL, `smtpSecure` VARCHAR(255) NULL COMMENT '\'ssl\'; // secure transfer enabled REQUIRED for Gmail', `smtpHost` VARCHAR(255) NULL COMMENT '\"smtp.gmail.com\"', `smtpUsername` VARCHAR(255) NULL COMMENT '\"email@gmail.com\"', `smtpPassword` VARCHAR(255) NULL, `smtpPort` INT NULL, `encoderURL` VARCHAR(255) NULL, PRIMARY KEY (`id`), INDEX `fk_configurations_users1_idx` (`users_id` ASC), CONSTRAINT `fk_configurations_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `videos_statistics` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `videos_statistics` ( `id` INT NOT NULL AUTO_INCREMENT, `when` DATETIME NOT NULL, `ip` VARCHAR(45) NULL, `users_id` INT NULL, `videos_id` INT NOT NULL, `created` DATETIME NULL DEFAULT NULL, `modified` DATETIME NULL DEFAULT NULL, `lastVideoTime` INT(11) NULL DEFAULT NULL, `session_id` VARCHAR(45) NOT NULL, `seconds_watching_video` INT(11) NULL DEFAULT NULL, + `json` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), INDEX `fk_videos_statistics_users1_idx` (`users_id` ASC), INDEX `fk_videos_statistics_videos1_idx` (`videos_id` ASC), INDEX `when_statisci` (`when` ASC), INDEX `session_id_statistics` (`session_id` ASC), INDEX `sec_watchin_videos` (`seconds_watching_video` ASC), CONSTRAINT `fk_videos_statistics_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_videos_statistics_videos1` FOREIGN KEY (`videos_id`) REFERENCES `videos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `likes` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `likes` ( `id` INT NOT NULL AUTO_INCREMENT, `like` INT(1) NOT NULL DEFAULT 0 COMMENT '1 = Like\n0 = Does not metter\n-1 = Dislike', `created` DATETIME NULL, `modified` DATETIME NULL, `videos_id` INT NOT NULL, `users_id` INT NOT NULL, PRIMARY KEY (`id`), INDEX `fk_likes_videos1_idx` (`videos_id` ASC), INDEX `fk_likes_users1_idx` (`users_id` ASC), INDEX `likes_likes_idx` (`like` ASC), CONSTRAINT `fk_likes_videos1` FOREIGN KEY (`videos_id`) REFERENCES `videos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_likes_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `users_groups` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `users_groups` ( `id` INT NOT NULL AUTO_INCREMENT, `group_name` VARCHAR(255) NULL, `created` DATETIME NULL, `modified` DATETIME NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `users_has_users_groups` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `users_has_users_groups` ( `users_id` INT NOT NULL, `users_groups_id` INT NOT NULL, PRIMARY KEY (`users_id`, `users_groups_id`), INDEX `fk_users_has_users_groups_users_groups1_idx` (`users_groups_id` ASC), INDEX `fk_users_has_users_groups_users1_idx` (`users_id` ASC), UNIQUE INDEX `index_user_groups_unique` (`users_groups_id` ASC, `users_id` ASC), CONSTRAINT `fk_users_has_users_groups_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_users_has_users_groups_users_groups1` FOREIGN KEY (`users_groups_id`) REFERENCES `users_groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `videos_group_view` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `videos_group_view` ( `id` INT NOT NULL AUTO_INCREMENT, `users_groups_id` INT NOT NULL, `videos_id` INT NOT NULL, INDEX `fk_videos_group_view_users_groups1_idx` (`users_groups_id` ASC), INDEX `fk_videos_group_view_videos1_idx` (`videos_id` ASC), PRIMARY KEY (`id`), CONSTRAINT `fk_videos_group_view_users_groups1` FOREIGN KEY (`users_groups_id`) REFERENCES `users_groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_videos_group_view_videos1` FOREIGN KEY (`videos_id`) REFERENCES `videos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `subscribes` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `subscribes` ( `id` INT NOT NULL AUTO_INCREMENT, `email` VARCHAR(100) NOT NULL, `status` ENUM('a', 'i') NOT NULL DEFAULT 'a', `created` DATETIME NULL, `modified` DATETIME NULL, `ip` VARCHAR(45) NULL, `users_id` INT NOT NULL DEFAULT 1 COMMENT 'subscribes to user channel', `notify` TINYINT(1) NOT NULL DEFAULT 1, `subscriber_users_id` INT(11) NOT NULL, PRIMARY KEY (`id`), INDEX `fk_subscribes_users1_idx` (`users_id` ASC), INDEX `fk_subscribes_users2_idx` (`subscriber_users_id` ASC), CONSTRAINT `fk_subscribes_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_subscribes_users2` FOREIGN KEY (`subscriber_users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `playlists` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `playlists` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `created` DATETIME NULL DEFAULT NULL, `modified` DATETIME NULL DEFAULT NULL, `users_id` INT(11) NOT NULL, `status` ENUM('public', 'private', 'unlisted', 'favorite', 'watch_later') NOT NULL DEFAULT 'public', `showOnTV` TINYINT NULL, PRIMARY KEY (`id`), INDEX `fk_playlists_users1_idx` (`users_id` ASC), INDEX `showOnTVindex3` (`showOnTV` ASC), CONSTRAINT `fk_playlists_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `playlists_has_videos` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `playlists_has_videos` ( `playlists_id` INT NOT NULL, `videos_id` INT NOT NULL, `order` INT NULL, PRIMARY KEY (`playlists_id`, `videos_id`), INDEX `fk_playlists_has_videos_videos1_idx` (`videos_id` ASC), INDEX `fk_playlists_has_videos_playlists1_idx` (`playlists_id` ASC), CONSTRAINT `fk_playlists_has_videos_playlists1` FOREIGN KEY (`playlists_id`) REFERENCES `playlists` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_playlists_has_videos_videos1` FOREIGN KEY (`videos_id`) REFERENCES `videos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `plugins` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `plugins` ( `id` INT NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(45) NOT NULL, `status` ENUM('active', 'inactive') NOT NULL DEFAULT 'active', `created` DATETIME NULL, `modified` DATETIME NULL, `object_data` TEXT NULL, `name` VARCHAR(255) NOT NULL, `dirName` VARCHAR(255) NOT NULL, `pluginversion` VARCHAR(6) NULL, PRIMARY KEY (`id`), UNIQUE INDEX `uuid_UNIQUE` (`uuid` ASC)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `comments_likes` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `comments_likes` ( `id` INT NOT NULL AUTO_INCREMENT, `like` INT(1) NOT NULL, `created` DATETIME NULL, `modified` DATETIME NULL, `users_id` INT NOT NULL, `comments_id` INT NOT NULL, PRIMARY KEY (`id`), INDEX `fk_comments_likes_users1_idx` (`users_id` ASC), INDEX `fk_comments_likes_comments1_idx` (`comments_id` ASC), CONSTRAINT `fk_comments_likes_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_comments_likes_comments1` FOREIGN KEY (`comments_id`) REFERENCES `comments` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `category_type_cache` -- ----------------------------------------------------- CREATE TABLE `category_type_cache` ( `categoryId` int(11) NOT NULL, `type` int(2) NOT NULL COMMENT '0=both, 1=audio, 2=video' DEFAULT 0, `manualSet` int(1) NOT NULL COMMENT '0=auto, 1=manual' DEFAULT 0 ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `categories_has_users_groups` ( `id` INT NOT NULL AUTO_INCREMENT, `categories_id` INT(11) NOT NULL, `users_groups_id` INT(11) NOT NULL, `created` DATETIME NULL, `modified` DATETIME NULL, `status` CHAR(1) NOT NULL DEFAULT 'a', PRIMARY KEY (`id`), INDEX `fk_categories_has_users_groups_users_groups1_idx` (`users_groups_id` ASC), INDEX `fk_categories_has_users_groups_categories1_idx` (`categories_id` ASC), CONSTRAINT `fk_categories_has_users_groups_categories1` FOREIGN KEY (`categories_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_categories_has_users_groups_users_groups1` FOREIGN KEY (`users_groups_id`) REFERENCES `users_groups` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; CREATE TABLE IF NOT EXISTS `users_extra_info` ( `id` INT NOT NULL AUTO_INCREMENT, `field_name` VARCHAR(45) NOT NULL, `field_type` VARCHAR(45) NOT NULL, `field_options` TEXT NULL, `field_default_value` VARCHAR(45) NULL, `parameters` TEXT NULL, `created` DATETIME NULL, `modified` DATETIME NULL, `status` CHAR(1) NOT NULL DEFAULT 'a', `order` INT NOT NULL DEFAULT 0, PRIMARY KEY (`id`), INDEX `ordersortusers_extra_info` USING BTREE (`order`)) ENGINE = InnoDB; ALTER TABLE `category_type_cache` ADD UNIQUE KEY `categoryId` (`categoryId`); ALTER TABLE `plugins` ADD INDEX `plugin_status` (`status` ASC); ALTER TABLE `videos` ADD INDEX `videos_status_index` (`status` ASC), ADD INDEX `is_suggested_index` (`isSuggested` ASC), ADD INDEX `views_count_index` (`views_count` ASC), ADD INDEX `filename_index` (`filename` ASC); COMMIT; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; diff --git a/objects/Object.php b/objects/Object.php index d2b155d60..3c9bd78f7 100644 --- a/objects/Object.php +++ b/objects/Object.php @@ -1,687 +1,691 @@ load($id); } } protected function load($id) { $row = self::getFromDb($id); if (empty($row)) { return false; } foreach ($row as $key => $value) { $this->$key = $value; } return true; } public static function getNowFromDB() { global $global; $sql = "SELECT NOW() as my_date_field"; $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } return $row; } public static function setTimeZone() { global $advancedCustom, $timezoneOriginal; if(!isset($timezoneOriginal)){ $timezoneOriginal = date_default_timezone_get(); } $row = self::getNowFromDB(); $dt = new DateTime($row['my_date_field']); if(!empty($_COOKIE['timezone']) && $_COOKIE['timezone'] !== 'undefined'){ $timezone = $_COOKIE['timezone']; }else{ $timeZOnesOptions = object_to_array($advancedCustom->timeZone->type); $timezone = $timeZOnesOptions[$advancedCustom->timeZone->value]; } if (empty($timezone) || $timezone == 'undefined') { return false; } try { $objDate = new DateTimeZone($timezone); if (is_object($objDate)) { $dt->setTimezone($objDate); date_default_timezone_set($timezone); return $dt; } return false; } catch (Exception $exc) { _error_log("setTimeZone: " . $exc->getMessage(), AVideoLog::$ERROR); return false; } } protected static function getFromDb($id) { global $global; $id = intval($id); $sql = "SELECT * FROM " . static::getTableName() . " WHERE id = ? LIMIT 1"; // I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about $res = sqlDAL::readSql($sql, "i", array($id), true); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } return $row; } public static function getAll() { global $global; if (!static::isTableInstalled()) { return false; } $sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } public static function getAllActive() { global $global; if (!static::isTableInstalled()) { return false; } $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='a' "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } public static function getTotal() { //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; if (!static::isTableInstalled()) { return 0; } $sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 "; $sql .= self::getSqlSearchFromPost(); $res = sqlDAL::readSql($sql); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); return $countRow; } public static function getSqlFromPost($keyPrefix = "") { global $global; $sql = self::getSqlSearchFromPost(); if (empty($_POST['sort']) && !empty($_GET['order'][0]['dir'])) { $index = intval($_GET['order'][0]['column']); $_GET['columns'][$index]['data']; $_POST['sort'][$_GET['columns'][$index]['data']] = $_GET['order'][0]['dir']; } // add a security here if (!empty($_POST['sort'])) { foreach ($_POST['sort'] as $key => $value) { $_POST['sort'][xss_esc($key)] = xss_esc($value); } } if (!empty($_POST['sort'])) { $orderBy = array(); foreach ($_POST['sort'] as $key => $value) { $key = $global['mysqli']->real_escape_string($key); //$value = $global['mysqli']->real_escape_string($value); $direction = "ASC"; if (strtoupper($value) === "DESC") { $direction = "DESC"; } $key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key); + $key = trim($key); + if (strpos($key, '.') === false) { + $key = "`{$key}`"; + } $orderBy[] = " {$keyPrefix}{$key} {$value} "; } $sql .= " ORDER BY " . implode(",", $orderBy); } $sql .= self::getSqlLimit(); return $sql; } public static function getSqlLimit() { global $global; $sql = ""; if (empty($_POST['rowCount']) && !empty($_GET['length'])) { $_POST['rowCount'] = intval($_GET['length']); } if (empty($_POST['current']) && !empty($_GET['start'])) { $_POST['current'] = ($_GET['start'] / $_GET['length']) + 1; } elseif (empty($_POST['current']) && isset($_GET['start'])) { $_POST['current'] = 1; } $_POST['current'] = getCurrentPage(); $_POST['rowCount'] = getRowCount(); if (!empty($_POST['rowCount']) && !empty($_POST['current']) && $_POST['rowCount'] > 0) { $_POST['rowCount'] = intval($_POST['rowCount']); $_POST['current'] = intval($_POST['current']); $current = ($_POST['current'] - 1) * $_POST['rowCount']; $current = $current < 0 ? 0 : $current; $sql .= " LIMIT $current, {$_POST['rowCount']} "; } else { $_POST['current'] = 0; $_POST['rowCount'] = 0; $sql .= " LIMIT 1000 "; } return $sql; } public static function getSqlSearchFromPost() { $sql = ""; if (!empty($_POST['searchPhrase'])) { $_GET['q'] = $_POST['searchPhrase']; } elseif (!empty($_GET['search']['value'])) { $_GET['q'] = $_GET['search']['value']; } if (!empty($_GET['q'])) { global $global; $search = $global['mysqli']->real_escape_string(xss_esc($_GET['q'])); $like = array(); $searchFields = static::getSearchFieldsNames(); foreach ($searchFields as $value) { $like[] = " {$value} LIKE '%{$search}%' "; // for accent insensitive $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; } if (!empty($like)) { $sql .= " AND (" . implode(" OR ", $like) . ")"; } else { $sql .= " AND 1=1 "; } } return $sql; } public function save() { if (!$this->tableExists()) { _error_log("Save error, table " . static::getTableName() . " does not exists", AVideoLog::$ERROR); return false; } global $global; $fieldsName = $this->getAllFields(); if (!empty($this->id)) { $sql = "UPDATE " . static::getTableName() . " SET "; $fields = array(); foreach ($fieldsName as $value) { if (strtolower($value) == 'created') { // do nothing } elseif (strtolower($value) == 'modified') { $fields[] = " {$value} = now() "; } elseif (is_numeric($this->$value)) { $fields[] = " `{$value}` = {$this->$value} "; } elseif (strtolower($this->$value) == 'null') { $fields[] = " `{$value}` = NULL "; } else { $fields[] = " `{$value}` = '{$this->$value}' "; } } $sql .= implode(", ", $fields); $sql .= " WHERE id = {$this->id}"; } else { $sql = "INSERT INTO " . static::getTableName() . " ( "; $sql .= "`" . implode("`,`", $fieldsName) . "` )"; $fields = array(); foreach ($fieldsName as $value) { if (strtolower($value) == 'created' || strtolower($value) == 'modified') { $fields[] = " now() "; } elseif (!isset($this->$value) || strtolower($this->$value) == 'null') { $fields[] = " NULL "; } else { $fields[] = " '{$this->$value}' "; } } $sql .= " VALUES (" . implode(", ", $fields) . ")"; } //if(static::getTableName() == 'subscriptions') echo $sql; $insert_row = sqlDAL::writeSql($sql); if ($insert_row) { if (empty($this->id)) { $id = $global['mysqli']->insert_id; } else { $id = $this->id; } return $id; } else { _error_log("ObjectYPT::save Error on save: " . $sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error, AVideoLog::$ERROR); return false; } } private function getAllFields() { global $global, $mysqlDatabase; $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = '" . static::getTableName() . "'"; $res = sqlDAL::readSql($sql, "s", array($mysqlDatabase)); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row["COLUMN_NAME"]; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } public function delete() { global $global; if (!empty($this->id)) { $sql = "DELETE FROM " . static::getTableName() . " "; $sql .= " WHERE id = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($this->id)); } _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); return false; } public static function setCache($name, $value) { $cachefile = self::getCacheFileName($name); make_path($cachefile); $content = _json_encode($value); if(empty($content)){ $content = $value; } $bytes = @file_put_contents($cachefile, $content); self::setSessionCache($name, $value); return array('bytes' => $bytes, 'cachefile' => $cachefile); } public static function cleanCacheName($name) { $name = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $name); $name = preg_replace('/[!#$&\'()*+,:;=?@[\\]% -]+/', '_', trim(strtolower(cleanString($name)))); $name = preg_replace('/\/{2,}/', '/', trim(strtolower(cleanString($name)))); if (function_exists('mb_ereg_replace')) { $name = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).\\/\\\])", '', $name); // Remove any runs of periods (thanks falstro!) $name = mb_ereg_replace("([\.]{2,})", '', $name); } return preg_replace('/[\x00-\x1F\x7F]/u', '', $name); } /** * * @param type $name * @param type $lifetime, if is = 0 it is unlimited * @return type */ public static function getCache($name, $lifetime = 60, $ignoreSessionCache = false) { if (isCommandLineInterface()) { return false; } if(isBot()){ $lifetime = 0; } global $getCachesProcessed, $_getCache; if (empty($_getCache)) { $_getCache = array(); } if (empty($getCachesProcessed)) { $getCachesProcessed = array(); } $cachefile = self::getCacheFileName($name); //_error_log('getCache: cachefile '.$cachefile); if (!empty($_getCache[$name])) { //_error_log('getCache: '.__LINE__); return $_getCache[$name]; } if (empty($getCachesProcessed[$name])) { $getCachesProcessed[$name] = 0; } $getCachesProcessed[$name]++; if (!empty($_GET['lifetime'])) { $lifetime = intval($_GET['lifetime']); } if (empty($ignoreSessionCache)) { $session = self::getSessionCache($name, $lifetime); if (!empty($session)) { $_getCache[$name] = $session; //_error_log('getCache: '.__LINE__); return $session; } } /* if (preg_match('/firstpage/i', $cachefile)) { echo var_dump($cachefile) . PHP_EOL; $trace = debug_backtrace(); $backtrace_lite = array(); foreach ($trace as $call) { echo $call['function'] . " " . $call['file'] . " line " . $call['line'] . PHP_EOL; }exit; } /** */ if (file_exists($cachefile) && (empty($lifetime) || time() - $lifetime <= filemtime($cachefile))) { //if(preg_match('/getStats/', $cachefile)){echo $cachefile,'
';} $c = @url_get_contents($cachefile); $json = _json_decode($c); if(empty($json) && !is_object($json) && !is_array($json)){ $json = $c; } self::setSessionCache($name, $json); $_getCache[$name] = $json; //_error_log('getCache: '.__LINE__); return $json; } elseif (file_exists($cachefile)) { self::deleteCache($name); @unlink($cachefile); } //if(preg_match('/getChannelsWithMoreViews30/i', $name)){var_dump($name, $cachefile, file_exists($cachefile) , $lifetime, time() - $lifetime, filemtime($cachefile));exit;} //_error_log("YPTObject::getCache log error [{$name}] $cachefile filemtime = ".filemtime($cachefile)); return null; } public static function deleteCache($name) { if(empty($name)){return false;} global $__getAVideoCache; unset($__getAVideoCache); $cachefile = self::getCacheFileName($name); @unlink($cachefile); self::deleteSessionCache($name); ObjectYPT::deleteCacheFromPattern($name); } static function deleteCachePattern($pattern) { global $__getAVideoCache; unset($__getAVideoCache); $tmpDir = self::getCacheDir(); $array = _glob($tmpDir, $pattern); foreach ($array as $value) { _error_log("Object::deleteCachePattern file [{$value}]"); @unlink($value); } _session_start(); foreach ($_SESSION['user']['sessionCache'] as $key => $value) { if (preg_match($pattern, $key)) { _error_log("Object::deleteCachePattern session [{$key}]"); $_SESSION['user']['sessionCache'][$key] = null; unset($_SESSION['user']['sessionCache'][$key]); } } } public static function deleteALLCache() { global $__getAVideoCache; unset($__getAVideoCache); $tmpDir = self::getCacheDir(); rrmdir($tmpDir); self::deleteAllSessionCache(); self::setLastDeleteALLCacheTime(); } public static function getCacheDir($filename = '') { global $_getCacheDir, $global; if (!isset($_getCacheDir)) { $_getCacheDir = array(); } if (!empty($_getCacheDir[$filename])) { return $_getCacheDir[$filename]; } $tmpDir = getTmpDir(); $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $tmpDir .= "YPTObjectCache" . DIRECTORY_SEPARATOR; $filename = self::cleanCacheName($filename); if (!empty($filename)) { $tmpDir .= $filename . DIRECTORY_SEPARATOR; $domain = getDomain(); $tmpDir .= $domain . DIRECTORY_SEPARATOR; // make sure you separete http and https cache $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http'; $tmpDir .= $protocol . DIRECTORY_SEPARATOR; if (class_exists("User_Location")) { $loc = User_Location::getThisUserLocation(); if (!empty($loc) && !empty($loc['country_code'])) { $tmpDir .= $loc['country_code'] . DIRECTORY_SEPARATOR; } } if (User::isLogged()) { if(User::isAdmin()){ $tmpDir .= 'admin_'.md5("admin".$global['salt']).DIRECTORY_SEPARATOR; }else{ $tmpDir .= 'user_'.md5("user".$global['salt']).DIRECTORY_SEPARATOR; } }else{ $tmpDir .= 'notlogged_'.md5("notlogged".$global['salt']).DIRECTORY_SEPARATOR; } } $tmpDir = fixPath($tmpDir); make_path($tmpDir); if (!file_exists($tmpDir . "index.html") && is_writable($tmpDir)) {// to avoid search into the directory _file_put_contents($tmpDir . "index.html", time()); } $_getCacheDir[$filename] = $tmpDir; return $tmpDir; } public static function getCacheFileName($name) { global $global; $tmpDir = self::getCacheDir($name); $uniqueHash = md5($name . $global['salt']); // add salt for security reasons return $tmpDir . $uniqueHash . '.cache'; } public static function deleteCacheFromPattern($name) { $tmpDir = getTmpDir(); $name = self::cleanCacheName($name); $ignoreLocationDirectoryName = (strpos($name, DIRECTORY_SEPARATOR) !== false); $filePattern = $tmpDir . DIRECTORY_SEPARATOR . $name; foreach (glob("{$filePattern}*") as $filename) { unlink($filename); } self::deleteSessionCache($name); } /** * Make sure you start the session before any output * @param type $name * @param type $value */ public static function setSessionCache($name, $value) { $name = self::cleanCacheName($name); _session_start(); $_SESSION['user']['sessionCache'][$name]['value'] = json_encode($value); $_SESSION['user']['sessionCache'][$name]['time'] = time(); if (empty($_SESSION['user']['sessionCache']['time'])) { $_SESSION['user']['sessionCache']['time'] = time(); } } /** * * @param type $name * @param type $lifetime, if is = 0 it is unlimited * @return type */ public static function getSessionCache($name, $lifetime = 60) { $name = self::cleanCacheName($name); if (!empty($_GET['lifetime'])) { $lifetime = intval($_GET['lifetime']); } if (!empty($_SESSION['user']['sessionCache'][$name])) { if ((empty($lifetime) || time() - $lifetime <= $_SESSION['user']['sessionCache'][$name]['time'])) { $c = $_SESSION['user']['sessionCache'][$name]['value']; $json = _json_decode($c); if(is_string($json) && strtolower($json) === 'false'){ $json = false; } return $json; } _session_start(); unset($_SESSION['user']['sessionCache'][$name]); } return null; } public static function clearSessionCache() { unset($_SESSION['user']['sessionCache']); } private static function getLastDeleteALLCacheTimeFile() { $tmpDir = getTmpDir(); $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . "/"; $tmpDir .= "lastDeleteALLCacheTime.cache"; return $tmpDir; } public static function setLastDeleteALLCacheTime() { $file = self::getLastDeleteALLCacheTimeFile(); //_error_log("ObjectYPT::setLastDeleteALLCacheTime {$file}"); return file_put_contents($file, time()); } public static function getLastDeleteALLCacheTime() { global $getLastDeleteALLCacheTime; if (empty($getLastDeleteALLCacheTime)) { $getLastDeleteALLCacheTime = (int) @file_get_contents(self::getLastDeleteALLCacheTimeFile(), time()); } return $getLastDeleteALLCacheTime; } public static function checkSessionCacheBasedOnLastDeleteALLCacheTime() { /* var_dump( $session_var['time'], self::getLastDeleteALLCacheTime(), humanTiming($session_var['time']), humanTiming(self::getLastDeleteALLCacheTime()), $session_var['time'] <= self::getLastDeleteALLCacheTime()); * */ if (empty($_SESSION['user']['sessionCache']['time']) || $_SESSION['user']['sessionCache']['time'] <= self::getLastDeleteALLCacheTime()) { self::deleteAllSessionCache(); return false; } return true; } public static function deleteSessionCache($name) { $name = self::cleanCacheName($name); _session_start(); $_SESSION['user']['sessionCache'][$name] = null; unset($_SESSION['user']['sessionCache'][$name]); } public static function deleteAllSessionCache() { _session_start(); unset($_SESSION['user']['sessionCache']); } public function tableExists() { return self::isTableInstalled(); } public static function isTableInstalled($tableName = "") { global $global, $tableExists; if (empty($tableName)) { $tableName = static::getTableName(); } if (empty($tableName)) { return false; } if (!isset($tableExists[$tableName])) { $sql = "SHOW TABLES LIKE '" . $tableName . "'"; //_error_log("isTableInstalled: ({$sql})"); $res = sqlDAL::readSql($sql); $result = sqlDal::num_rows($res); sqlDAL::close($res); $tableExists[$tableName] = !empty($result); } return $tableExists[$tableName]; } static function clientTimezoneToDatabaseTimezone($clientDate){ if(!preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/', $clientDate)){ return $clientDate; } global $timezoneOriginal; $currentTimezone = date_default_timezone_get(); $time = strtotime($clientDate); date_default_timezone_set($timezoneOriginal); $dbDate = date('Y-m-d H:i:s', $time); date_default_timezone_set($currentTimezone); return $dbDate; } } //abstract class Object extends ObjectYPT{}; diff --git a/objects/user.php b/objects/user.php index 00264cdd4..8f3b59b78 100644 --- a/objects/user.php +++ b/objects/user.php @@ -1,2397 +1,2405 @@ user = $user; if ($password !== false) { $this->password = $password; } else { $this->loadFromUser($user); } } else { // get data from id $this->load($id); } } public function getEmail() { return $this->email; } public function getUser() { return $this->user; } public function getAbout() { return str_replace(array('\\\\\\\n'), array("\n"), $this->about); } public function setAbout($about) { $this->about = xss_esc($about); } public function getPassword() { return $this->password; } public function getCanStream() { return $this->canStream; } public function setCanStream($canStream) { $this->canStream = (empty($canStream) || strtolower($canStream) === 'false') ? 0 : 1; } public function getCanViewChart() { return $this->canViewChart; } public function setCanViewChart($canViewChart) { $this->canViewChart = (empty($canViewChart) || strtolower($canViewChart) === 'false') ? 0 : 1; } public function getCanCreateMeet() { return $this->canCreateMeet; } public function setCanCreateMeet($canCreateMeet) { $this->canCreateMeet = (empty($canCreateMeet) || strtolower($canCreateMeet) === 'false') ? 0 : 1; ; } public function getCanUpload() { return $this->canUpload; } public function setCanUpload($canUpload) { $this->canUpload = (empty($canUpload) || strtolower($canUpload) === 'false') ? 0 : 1; } public function getAnalyticsCode() { return $this->analyticsCode; } public function setAnalyticsCode($analyticsCode) { preg_match("/(ua-\d{4,9}-\d{1,4})/i", $analyticsCode, $matches); if (!empty($matches[1])) { $this->analyticsCode = $matches[1]; } else { $this->analyticsCode = ""; } } public function getAnalytics() { $id = $this->getId(); $aCode = $this->getAnalyticsCode(); if (!empty($id) && !empty($aCode)) { $code = " "; } else { $code = ""; } return $code; } public function addExternalOptions($id, $value) { $eo = unserialize(base64_decode($this->externalOptions)); if (!is_array($eo)) { $eo = array(); } $eo[$id] = $value; $this->setExternalOptions($eo); return $this->save(); } public function removeExternalOptions($id) { $eo = unserialize(base64_decode($this->externalOptions)); unset($eo[$id]); $this->setExternalOptions($eo); return $this->save(); } public function setExternalOptions($options) { //we convert it to base64 to sanitize the input since we do not validate input from externalOptions $this->externalOptions = base64_encode(serialize($options)); } public function getExternalOption($id) { $eo = unserialize(base64_decode($this->externalOptions)); if (empty($eo[$id])) { return null; } return $eo[$id]; } private function load($id) { $id = intval($id); if (empty($id)) { return false; } $user = self::getUserDb($id); if (empty($user)) { return false; } foreach ($user as $key => $value) { $this->$key = $value; } return true; } private function loadFromUser($user) { $userLoaded = self::getUserDbFromUser($user); if (empty($userLoaded)) { return false; } _error_log("User::loadFromUser($user) "); _error_log("User::loadFromUser json " . json_encode(debug_backtrace())); foreach ($userLoaded as $key => $value) { $this->$key = $value; } return true; } public function loadSelfUser() { $this->load($this->getId()); } public static function getId() { if (self::isLogged()) { return $_SESSION['user']['id']; } else { return false; } } public static function getEmail_() { if (self::isLogged()) { return $_SESSION['user']['email']; } else { return false; } } public function getBdId() { return $this->id; } public static function updateSessionInfo() { if (self::isLogged()) { $user = self::getUserDb($_SESSION['user']['id']); $_SESSION['user'] = $user; } } public static function getName() { if (self::isLogged()) { return $_SESSION['user']['name']; } else { return false; } } public static function getUserName() { if (self::isLogged()) { return $_SESSION['user']['user']; } else { return false; } } public static function getUserChannelName() { if (self::isLogged()) { if (empty($_SESSION['user']['channelName'])) { $_SESSION['user']['channelName'] = self::_recommendChannelName(); $user = new User(User::getId()); $user->setChannelName($_SESSION['user']['channelName']); $user->save(); } return $_SESSION['user']['channelName']; } else { return false; } } public static function _recommendChannelName($name = "", $try = 0, $unknown = "", $users_id = 0) { if (empty($users_id)) { if (!empty(User::getId())) { $users_id = User::getId(); } } if (empty($users_id)) { $newChannelName = $name . "_" . uniqid(); if (strlen($newChannelName) > 40) { $newChannelName = uniqid(); } return $newChannelName; } if ($try > 10) { _error_log("User:_recommendChannelName too many tries ({$name}) (" . User::getId() . ") ", AVideoLog::$ERROR); return uniqid(); } if (empty($name)) { $name = self::getNameIdentification(); if ($name == __("Unknown User") && !empty($unknown)) { $name = $unknown; } $name = cleanString($name); } // in case is a email get only the username $parts = explode("@", $name); $name = $parts[0]; // do not exceed 36 chars to leave some room for the unique id; $name = substr($name, 0, 36); if (!Permissions::canAdminUsers()) { $user = self::getUserFromChannelName($name); if ($user && $user['id'] !== $users_id) { return self::_recommendChannelName($name . "_" . uniqid(), $try + 1); } } return $name; } public static function getUserFromChannelName($channelName) { $channelName = cleanString($channelName); global $global; $channelName = ($channelName); $sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($channelName)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { $user = cleanUpRowFromDatabase($user); return $user; } else { return false; } } /** * return an name to identify the user * @return String */ public static function getNameIdentification() { global $advancedCustomUser; if (self::isLogged()) { if (!empty(self::getName()) && empty($advancedCustomUser->doNotIndentifyByName)) { return self::getName(); } if (!empty(self::getMail()) && empty($advancedCustomUser->doNotIndentifyByEmail)) { return self::getMail(); } if (!empty(self::getUserName()) && empty($advancedCustomUser->doNotIndentifyByUserName)) { return self::getUserName(); } if (!empty(self::getUserChannelName())) { return self::getUserChannelName(); } } return __("Unknown User"); } /** * return an name to identify the user from database * @return String */ public function getNameIdentificationBd() { global $advancedCustomUser; if (!empty($this->name) && empty($advancedCustomUser->doNotIndentifyByName)) { return $this->name; } if (!empty($this->email) && empty($advancedCustomUser->doNotIndentifyByEmail)) { return $this->email; } if (!empty($this->user) && empty($advancedCustomUser->doNotIndentifyByUserName)) { return $this->user; } if (!empty($this->channelName)) { return $this->channelName; } return __("Unknown User"); } public static function getNameIdentificationById($id = "") { if (!empty($id)) { $user = new User($id); return $user->getNameIdentificationBd(); } return __("Unknown User"); } public static function getUserPass() { if (self::isLogged()) { return $_SESSION['user']['password']; } else { return false; } } public function _getName() { return $this->name; } public function getBdName() { return $this->_getName(); } public static function _getPhoto($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['photoURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['photoURL']; } if (!empty($photo)) { if (preg_match("/videos\/userPhoto\/.*/", $photo) && file_exists($global['systemRootPath'] . $photo)) { return $photo; } else { $photoPath = "/videos/userPhoto/photo{$id}.png"; $content = url_get_contents($photo); file_put_contents($global['systemRootPath'] . $photoPath, $content); $photo = $photoPath; } } if (empty($photo)) { $photo = "view/img/userSilhouette.jpg"; } return $photo; } public static function getPhoto($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['photoURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['photoURL']; } if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) { if (file_exists($global['systemRootPath'] . $photo)) { $photo = getCDN() . $photo . "?" . filemtime($global['systemRootPath'] . $photo); } else { $photo = ""; } } if (empty($photo)) { $photo = getCDN() . "view/img/userSilhouette.jpg"; } return $photo; } public static function _getOGImage($users_id) { return "/videos/userPhoto/photo{$users_id}_og_200X200.jpg"; } public static function deleteOGImage($users_id) { global $global; $photo = $global['systemRootPath'] . self::_getOGImage($users_id); @unlink($photo); } public static function getOGImage($users_id = "") { global $global; $photo = self::_getPhoto($users_id); if ($photo == "view/img/userSilhouette.jpg") { return getCDN() . "view/img/userSilhouette.jpg"; } if (empty($photo)) { return false; } $source = $global['systemRootPath'] . $photo; $destination = $global['systemRootPath'] . self::_getOGImage($users_id); convertImageToOG($source, $destination); return getCDN() . self::_getOGImage($users_id); } public static function getEmailVerifiedIcon($id = "") { global $advancedCustomUser; $mark = ""; if (!empty($advancedCustomUser->showEmailVerifiedMark)) { if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $verified = $user['emailVerified']; } } elseif (self::isLogged()) { $verified = $_SESSION['user']['emailVerified']; } if (!empty($verified)) { $mark .= ' '; } else { //return ''; $mark .= ''; } } if ($advancedCustomUser->Checkmark1Enabled) { if (User::externalOptionsFromUserID($id, "checkmark1")) { $mark .= " " . $advancedCustomUser->Checkmark1HTML; } } if ($advancedCustomUser->Checkmark2Enabled) { if (User::externalOptionsFromUserID($id, "checkmark2")) { $mark .= " " . $advancedCustomUser->Checkmark2HTML; } } if ($advancedCustomUser->Checkmark3Enabled) { if (User::externalOptionsFromUserID($id, "checkmark3")) { $mark .= " " . $advancedCustomUser->Checkmark3HTML; } } return $mark; } public function getPhotoDB() { global $global; $photo = self::getPhoto($this->id); return $photo; } public static function getBackground($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['backgroundURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['backgroundURL']; } if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) { if (file_exists($global['systemRootPath'] . $photo)) { $photo = getCDN() . $photo; } else { $photo = ""; } } if (empty($photo)) { $photo = getCDN() . "view/img/background.png"; } return $photo; } public static function getMail() { if (self::isLogged()) { return $_SESSION['user']['email']; } else { return false; } } public function save($updateUserGroups = false) { global $global, $config, $advancedCustom, $advancedCustomUser; if (is_object($config) && $config->currentVersionLowerThen('5.6')) { // they dont have analytics code return false; } if (empty($this->user) || empty($this->password)) { //echo "u:" . $this->user . "|p:" . strlen($this->password); - _error_log('Error : ' . __("You need a user and passsword to register")); + if (empty($this->user)) { + //echo "u:" . $this->user . "|p:" . strlen($this->password); + _error_log('Error : 1 ' . __("You need a user and passsword to register")); + return false; + } + if (empty($this->password)) { + //echo "u:" . $this->user . "|p:" . strlen($this->password); + _error_log('Error : 2 ' . __("You need a user and passsword to register")); + return false; + } + return false; } if (empty($this->isAdmin)) { $this->isAdmin = "false"; } if (empty($this->canStream)) { if (empty($this->id)) { // it is a new user if (empty($advancedCustomUser->newUsersCanStream)) { $this->canStream = "0"; } else { $this->canStream = "1"; } } else { $this->canStream = "0"; } } if (empty($this->canUpload)) { $this->canUpload = "0"; } if (empty($this->status)) { $this->status = 'a'; } if (empty($this->emailVerified)) { $this->emailVerified = "false"; } $user = ($this->user); - $password = ($this->password); - $name = ($this->name); + $password = ($this->password); + $name = ($this->name); $status = ($this->status); $this->about = preg_replace("/(\\\)+n/", "\n", $this->about); $this->channelName = self::_recommendChannelName($this->channelName, 0, $this->user, $this->id); $channelName = ($this->channelName); if (filter_var($this->donationLink, FILTER_VALIDATE_URL) === false) { $this->donationLink = ""; } if (!empty($this->id)) { $formats = "ssssiiii"; $values = array($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet); $sql = "UPDATE users SET user = ?, password = ?, " . "email = ?, name = ?, isAdmin = ?," . "canStream = ?,canUpload = ?,canCreateMeet = ?,"; if (isset($this->canViewChart)) { $formats .= "i"; $values[] = $this->canViewChart; $sql .= "canViewChart = ?, "; } $formats .= "ssssssissssssssssi"; $values[] = $this->status; $values[] = $this->photoURL; $values[] = $this->backgroundURL; $values[] = $this->recoverPass; $values[] = $this->about; $values[] = $this->channelName; $values[] = $this->emailVerified; $values[] = $this->analyticsCode; $values[] = $this->externalOptions; $values[] = $this->first_name; $values[] = $this->last_name; $values[] = $this->address; $values[] = $this->zip_code; $values[] = $this->country; $values[] = $this->region; $values[] = $this->city; $values[] = $this->donationLink; $values[] = $this->id; $sql .= "status = ?, " . "photoURL = ?, backgroundURL = ?, " . "recoverPass = ?, about = ?, " . " channelName = ?, emailVerified = ? , analyticsCode = ?, externalOptions = ? , " . " first_name = ? , last_name = ? , address = ? , zip_code = ? , country = ? , region = ? , city = ? , donationLink = ? , " . " modified = now() WHERE id = ?"; } else { $formats = "ssssiiiissssss"; $values = array($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet, $status, $this->photoURL, $this->recoverPass, $channelName, $this->analyticsCode, $this->externalOptions); $sql = "INSERT INTO users (user, password, email, name, isAdmin, canStream, canUpload, canCreateMeet, canViewChart, status,photoURL,recoverPass, created, modified, channelName, analyticsCode, externalOptions) " . " VALUES (?,?,?,?,?,?,?,?, false, " . "?,?,?, now(), now(),?,?,?)"; } $insert_row = sqlDAL::writeSql($sql, $formats, $values); if ($insert_row) { if (empty($this->id)) { $id = $global['mysqli']->insert_id; if (!empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) { self::sendVerificationLink($id); } } else { $id = $this->id; } if ($updateUserGroups) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; // update the user groups UserGroups::updateUserGroups($id, $this->userGroups); } return $id; } else { _error_log(' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql"); return false; } } public static function getChannelOwner($channelName) { global $global; $channelName = ($channelName); $sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($channelName)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $result = cleanUpRowFromDatabase($result); $user = $result; } else { $user = false; } return $user; } public static function getFromUsername($user) { global $global; $user = ($user); $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $result = cleanUpRowFromDatabase($result); $user = $result; } else { $user = false; } return $user; } private static function setCacheWatchVideo($cacheName, $value) { if (!User::isLogged()) { ObjectYPT::setCache($cacheName, $value); ; } else { ObjectYPT::setSessionCache($cacheName, $value); } } public static function canWatchVideo($videos_id) { $cacheName = "canWatchVideo$videos_id"; if (!User::isLogged()) { $cacheName = "canWatchVideoNOTLOGED$videos_id"; $cache = ObjectYPT::getCache($cacheName, 3600); } else { $cache = ObjectYPT::getSessionCache($cacheName, 600); } if (isset($cache)) { - if($cache === 'false'){ + if ($cache === 'false') { $cache = false; } return $cache; } if (empty($videos_id)) { _error_log("User::canWatchVideo Video is empty ({$videos_id})"); return false; } if (User::isAdmin()) { return true; } $video = new Video("", "", $videos_id); if ($video->getStatus() === 'i') { _error_log("User::canWatchVideo Video is inactive ({$videos_id})"); self::setCacheWatchVideo($cacheName, false); return false; } $user = new User($video->getUsers_id()); if ($user->getStatus() === 'i') { _error_log("User::canWatchVideo User is inactive ({$videos_id})"); self::setCacheWatchVideo($cacheName, false); return false; } if (AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) { self::setCacheWatchVideo($cacheName, true); return true; } // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { // check if any plugin restrict access to this video if (!AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) { if (User::isLogged()) { _error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [" . User::getId() . "] can not see ({$videos_id})"); } else { _error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [not logged] can not see ({$videos_id})"); } self::setCacheWatchVideo($cacheName, false); return false; } else { self::setCacheWatchVideo($cacheName, true); return true; // the video is public } } if (!User::isLogged()) { _error_log("User::canWatchVideo You are not logged so can not see ({$videos_id}) session_id=" . session_id() . " SCRIPT_NAME=" . $_SERVER["SCRIPT_NAME"] . " IP = " . getRealIpAddr()); self::setCacheWatchVideo($cacheName, false); return false; } // if is not public check if the user is on one of its groups $rowsUser = UserGroups::getUserGroups(User::getId()); foreach ($rows as $value) { foreach ($rowsUser as $value2) { if ($value['id'] === $value2['id']) { self::setCacheWatchVideo($cacheName, true); return true; } } } _error_log("User::canWatchVideo The user " . User::getId() . " is not on any of the user groups ({$videos_id}) " . json_encode($rows)); self::setCacheWatchVideo($cacheName, false); return false; } public static function canWatchVideoWithAds($videos_id) { if (empty($videos_id)) { _error_log("User::canWatchVideo (videos_id is empty) " . $videos_id); return false; } if (User::isAdmin()) { return true; } if (AVideoPlugin::userCanWatchVideoWithAds(User::getId(), $videos_id)) { //_error_log("User::userCanWatchVideoWithAds (can) " . User::getId() . " " . $videos_id); return true; } _error_log("User::userCanWatchVideoWithAds (No can not) " . User::getId() . " " . $videos_id); if (self::canWatchVideo($videos_id)) { //_error_log("User::canWatchVideo (can) " . $videos_id); return true; } _error_log("User::canWatchVideo (No can not) " . $videos_id); return false; } public function delete() { if (!self::isAdmin()) { return false; } // cannot delete yourself if (self::getId() === $this->id) { return false; } global $global; if (!empty($this->id)) { $sql = "DELETE FROM users WHERE id = ?"; } else { return false; } return sqlDAL::writeSql($sql, "i", array($this->id)); } const USER_LOGGED = 0; const USER_NOT_VERIFIED = 1; const USER_NOT_FOUND = 2; const CAPTCHA_ERROR = 3; const REQUIRE2FA = 4; public function login($noPass = false, $encodedPass = false, $ignoreEmailVerification = false) { if (User::isLogged()) { return false; } global $global, $advancedCustom, $advancedCustomUser, $config; if (strtolower($encodedPass) === 'false') { $encodedPass = false; } //_error_log("user::login: noPass = $noPass, encodedPass = $encodedPass, this->user, $this->user " . getRealIpAddr()); if ($noPass) { $user = $this->find($this->user, false, true); } else { $user = $this->find($this->user, $this->password, true, $encodedPass); } if (!self::checkLoginAttempts()) { return self::CAPTCHA_ERROR; } ObjectYPT::clearSessionCache(); _session_start(); // check for multiple logins attempts to prevent hacking end // if user is not verified if (empty($ignoreEmailVerification) && !empty($user) && empty($user['isAdmin']) && empty($user['emailVerified']) && !empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) { unset($_SESSION['user']); self::sendVerificationLink($user['id']); return self::USER_NOT_VERIFIED; } elseif ($user) { $_SESSION['user'] = $user; $this->setLastLogin($_SESSION['user']['id']); $rememberme = 0; if ((!empty($_POST['rememberme']) && $_POST['rememberme'] == "true") || !empty($_COOKIE['rememberme'])) { $expires = strtotime("+ 1 year"); $rememberme = 1; } else { $expires = 0; } _setcookie("rememberme", $rememberme, $expires); _setcookie("user", $user['user'], $expires); _setcookie("pass", $user['password'], $expires); AVideoPlugin::onUserSignIn($_SESSION['user']['id']); $_SESSION['loginAttempts'] = 0; session_write_close(); return self::USER_LOGGED; } else { unset($_SESSION['user']); return self::USER_NOT_FOUND; } } public static function isCaptchaNeed() { global $advancedCustomUser; // check for multiple logins attempts to prevent hacking if (!empty($_SESSION['loginAttempts']) && !empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) { if (isMobile()) { $advancedCustomUser->requestCaptchaAfterLoginsAttempts += 10; } if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) { return true; } } return false; } public static function checkLoginAttempts() { global $advancedCustomUser, $global; // check for multiple logins attempts to prevent hacking if (empty($_SESSION['loginAttempts'])) { _session_start(); $_SESSION['loginAttempts'] = 0; } if (!empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) { _session_start(); $_SESSION['loginAttempts']++; if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) { if (empty($_POST['captcha'])) { return false; } require_once $global['systemRootPath'] . 'objects/captcha.php'; if (!Captcha::validation($_POST['captcha'])) { return false; } } } return true; } public static function getCaptchaFormIfNeed() { // check for multiple logins attempts to prevent hacking if (self::isCaptchaNeed()) { return self::getCaptchaForm(); } return ""; } public static function getCaptchaForm($uid = "") { global $global; return '
' . '
'; } private function setLastLogin($user_id) { global $global; if (empty($user_id)) { die('Error : setLastLogin '); } $sql = "UPDATE users SET lastLogin = now(), modified = now() WHERE id = ?"; return sqlDAL::writeSql($sql, "i", array($user_id)); } public static function logoff() { global $global, $justLogoff; $justLogoff = true; _session_start(); ObjectYPT::deleteAllSessionCache(); _unsetcookie('rememberme'); _unsetcookie('user'); _unsetcookie('pass'); unset($_SESSION['user']); } private static function recreateLoginFromCookie() { global $justLogoff, $justTryToRecreateLoginFromCookie; if (empty($justTryToRecreateLoginFromCookie) && empty($justLogoff) && empty($_SESSION['user']['id'])) { $justTryToRecreateLoginFromCookie = 1; // first check if the LoginControl::singleDeviceLogin is enabled, if it is only recreate login if the device is the last device if ($obj = AVideoPlugin::getDataObjectIfEnabled("LoginControl")) { if (!empty($obj->singleDeviceLogin)) { if (!LoginControl::isLoggedFromSameDevice()) { _error_log("user::recreateLoginFromCookie: LoginControl and the last logged device is different: " . $_COOKIE['user'] . ""); self::logoff(); return false; } } } if ((!empty($_COOKIE['user'])) && (!empty($_COOKIE['pass'])) && (!empty($_COOKIE['rememberme']))) { $user = new User(0, $_COOKIE['user'], false); $user->setPassword($_COOKIE['pass'], true); // $dbuser = self::getUserDbFromUser($_COOKIE['user']); $resp = $user->login(false, true); _error_log("user::recreateLoginFromCookie: do cookie-login: " . $_COOKIE['user'] . " result: " . $resp); if (0 == $resp) { _error_log("success " . $_SESSION['user']['id']); } else { _error_log("user::recreateLoginFromCookie: do logoff: " . $_COOKIE['user'] . " result: " . $resp); self::logoff(); } } } } public static function isLogged() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['id']); } public static function isVerified() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['emailVerified']); } - public static function isAdmin($users_id=0) { - if(!empty($users_id)){ + public static function isAdmin($users_id = 0) { + if (!empty($users_id)) { $user = new User($users_id); return !empty($user->getIsAdmin()); } - + self::recreateLoginFromCookie(); return !empty($_SESSION['user']['isAdmin']); } public static function canStream() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['isAdmin']) || !empty($_SESSION['user']['canStream']); } public static function externalOptions($id) { if (!empty($_SESSION['user']['externalOptions'])) { $externalOptions = unserialize(base64_decode($_SESSION['user']['externalOptions'])); if (isset($externalOptions[$id])) { if ($externalOptions[$id] == "true") { $externalOptions[$id] = true; } elseif ($externalOptions[$id] == "false") { $externalOptions[$id] = false; } return $externalOptions[$id]; } } return false; } public static function externalOptionsFromUserID($users_id, $id) { $user = self::findById($users_id); if ($user) { if (!is_null($user['externalOptions'])) { $externalOptions = unserialize(base64_decode($user['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($id != $k) { continue; } if ($v == "true") { $v = 1; } elseif ($v == "false") { $v = 0; } return $v; } } } } return false; } public function thisUserCanStream() { if ($this->status === 'i') { return false; } return !empty($this->isAdmin) || !empty($this->canStream); } private function find($user, $pass, $mustBeactive = false, $encodedPass = false) { global $global, $advancedCustom; $formats = ""; $values = array(); $sql = "SELECT * FROM users WHERE user = ? "; $formats .= "s"; $values[] = $user; if ($mustBeactive) { $sql .= " AND status = 'a' "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, $formats, $values, true); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { if ($pass !== false) { if (!encryptPasswordVerify($pass, $result['password'], $encodedPass)) { if (!empty($advancedCustom) && $advancedCustom->enableOldPassHashCheck) { _error_log("Password check new hash pass does not match, trying MD5"); return $this->find_Old($user, $pass, $mustBeactive, $encodedPass); } else { return false; } } } $user = $result; } else { _error_log("Password check new hash user not found"); //check if is the old password style $user = false; //$user = false; } return $user; } /** * this is the deprecated function, with week password * @global type $global * @param type $user * @param type $pass * @param type $mustBeactive * @param type $encodedPass * @return boolean */ private function find_Old($user, $pass, $mustBeactive = false, $encodedPass = false) { global $global; $formats = ""; $values = array(); $sql = "SELECT * FROM users WHERE user = ? "; $formats .= "s"; $values[] = $user; if ($mustBeactive) { $sql .= " AND status = 'a' "; } if ($pass !== false) { if (!$encodedPass || $encodedPass === 'false') { _error_log("Password check Old not encoded pass"); $passEncoded = md5($pass); } else { _error_log("Password check Old encoded pass"); $passEncoded = $pass; } $sql .= " AND password = ? "; $formats .= "s"; $values[] = $passEncoded; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, $formats, $values, true); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { if (!$encodedPass || $encodedPass === 'false') { //update the password $u = new User($result['id']); $u->setPassword($pass); $u->save(); $result['password'] = $u->getPassword(); } $user = $result; } else { $user = false; } if (empty($user)) { _error_log("Password check Old not found"); } else { _error_log("Password check Old found"); } return $user; } private static function findById($id) { global $global; $id = intval($id); if (empty($id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $user = $result; } else { $user = false; } return $user; } public static function findByEmail($email) { global $global; $email = trim($email); if (empty($email)) { return false; } $sql = "SELECT * FROM users WHERE email = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($email)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { $user = $result; } else { $user = false; } return $user; } private static function getUserDb($id) { global $global; $id = intval($id); if (empty($id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1;"; $res = sqlDAL::readSql($sql, "i", array($id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } private static function getUserDbFromUser($user) { global $global; if (empty($user)) { return false; } $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } public static function getUserFromID($users_id) { global $global; if (empty($users_id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($users_id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { $user['groups'] = UserGroups::getUserGroups($user['id']); $user['identification'] = self::getNameIdentificationById($user['id']); $user['photo'] = self::getPhoto($user['id']); $user['background'] = self::getBackground($user['id']); $user['tags'] = self::getTags($user['id']); $user['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $user['name']); $user['isEmailVerified'] = $user['emailVerified']; if (!is_null($user['externalOptions'])) { $externalOptions = unserialize(base64_decode($user['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($v == "true") { $v = 1; } elseif ($v == "false") { $v = 0; } $user[$k] = $v; } } } unset($user['password'], $user['recoverPass']); if (!Permissions::canAdminUsers() && $user['id'] !== User::getId()) { unset( - $user['first_name'], - $user['last_name'], - $user['address'], - $user['zip_code'], - $user['country'], - $user['region'], - $user['city'] + $user['first_name'], + $user['last_name'], + $user['address'], + $user['zip_code'], + $user['country'], + $user['region'], + $user['city'] ); } return $user; } return false; } public static function getUserFromEmail($email) { $email = trim($email); $sql = "SELECT * FROM users WHERE email = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($email)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } public function setUser($user) { global $advancedCustomUser; if (empty($advancedCustomUser->userCanChangeUsername)) { if (!empty($this->user)) { return false; } } $this->user = strip_tags($user); } public function setName($name) { $this->name = strip_tags($name); } public function setEmail($email) { global $advancedCustomUser; $email = strip_tags($email); if (!empty($advancedCustomUser->emailMustBeUnique)) { if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } $userFromEmail = User::getUserFromEmail($email); if (!empty($userFromEmail)) { return false; } } $this->email = $email; return true; } public function setPassword($password, $doNotEncrypt = false) { if (!empty($password)) { if ($doNotEncrypt) { $this->password = ($password); } else { $this->password = encryptPassword($password); } } } public function setIsAdmin($isAdmin) { if (empty($isAdmin) || $isAdmin === "false" || !User::isAdmin()) { $isAdmin = "0"; } else { $isAdmin = "1"; } $this->isAdmin = $isAdmin; } public function setStatus($status) { $this->status = strip_tags($status); } public function getPhotoURL() { return $this->photoURL; } public function setPhotoURL($photoURL) { $this->photoURL = strip_tags($photoURL); } public static function getAllUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } $users_groups_id = intval($users_groups_id); if (empty($users_groups_id)) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users u WHERE 1=1 "; $sql .= " AND (id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); - if(!empty($ids) && is_array($ids)){ + if (!empty($ids) && is_array($ids)) { $ids = array_unique($ids); - $sql .= " OR id IN ('". implode("','", $ids)."') "; + $sql .= " OR id IN ('" . implode("','", $ids) . "') "; } $sql .= " ) "; - + if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND u.status = 'i' "; } else { $sql .= " AND u.status = 'a' "; } } - + $sql .= BootGrid::getSqlFromPost($searchFields); $user = array(); require_once $global['systemRootPath'] . 'objects/userGroups.php'; $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = self::getUserInfoFromRow($row); } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } public static function getTotalUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } $users_groups_id = intval($users_groups_id); if (empty($users_groups_id)) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT id FROM users WHERE 1=1 "; $sql .= " AND (id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); - if(!empty($ids) && is_array($ids)){ + if (!empty($ids) && is_array($ids)) { $ids = array_unique($ids); - $sql .= " OR id IN ('". implode("','", $ids)."') "; + $sql .= " OR id IN ('" . implode("','", $ids) . "') "; } $sql .= " ) "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user')); $res = sqlDAL::readSql($sql); $result = sqlDal::num_rows($res); sqlDAL::close($res); - + return $result; } public static function getAllUsers($ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users WHERE 1=1 "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlFromPost($searchFields); $user = array(); require_once $global['systemRootPath'] . 'objects/userGroups.php'; $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = self::getUserInfoFromRow($row); } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } - - public static function getAllActiveUsersThatCanUpload() { if (!Permissions::canAdminUsers()) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users WHERE 1=1 AND status = 'a' AND (canUpload = 1 OR isAdmin = 1) "; $user = array(); $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = $row; } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } private static function getUserInfoFromRow($row) { $row['groups'] = UserGroups::getUserGroups($row['id']); $row['identification'] = self::getNameIdentificationById($row['id']); $row['photo'] = self::getPhoto($row['id']); $row['background'] = self::getBackground($row['id']); $row['tags'] = self::getTags($row['id']); $row['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['name']); $row['isEmailVerified'] = $row['emailVerified']; if (!is_null($row['externalOptions'])) { $externalOptions = unserialize(base64_decode($row['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($v == "true") { $v = 1; } elseif ($v == "false") { $v = 0; } $row[$k] = $v; } } } unset($row['password'], $row['recoverPass']); if (!Permissions::canAdminUsers() && $row['id'] !== User::getId()) { unset( - $row['first_name'], - $row['last_name'], - $row['address'], - $row['zip_code'], - $row['country'], - $row['region'], - $row['city'] + $row['first_name'], + $row['last_name'], + $row['address'], + $row['zip_code'], + $row['country'], + $row['region'], + $row['city'] ); } return $row; } public static function getAllUsersThatHasVideos($ignoreAdmin = false) { if (!self::isAdmin() && !$ignoreAdmin) { return false; } global $global; $sql = "SELECT * FROM users u WHERE status = 'a' AND (canUpload = 1 || isAdmin = 1) AND " . " (SELECT count(id) FROM videos where users_id = u.id )>0 "; $user = array(); $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = $row; } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } public static function getTotalUsers($ignoreAdmin = false, $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT id FROM users WHERE 1=1 "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user')); $res = sqlDAL::readSql($sql); $result = sqlDal::num_rows($res); sqlDAL::close($res); return $result; } public static function userExists($user) { global $global; $user = ($user); $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user['id']; } else { return false; } } public static function idExists($users_id) { global $global; $users_id = intval($users_id); $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($users_id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user['id']; } else { return false; } } public static function createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false) { global $global, $advancedCustomUser; $userId = 0; if (!$userId = self::userExists($user)) { if (empty($pass)) { $pass = uniqid(); } $pass = encryptPassword($pass); $userObject = new User(0, $user, $pass); $userObject->setEmail($email); $userObject->setName($name); $userObject->setIsAdmin($isAdmin); $userObject->setPhotoURL($photoURL); $userObject->setEmailVerified($emailVerified); $userId = $userObject->save(); if (!empty($userId)) { if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup UserGroups::updateUserGroups($userId, array($advancedCustomUser->userDefaultUserGroup->value), true); } } return $userId; } else { if ($emailVerified) { $userObj = new User($userId); if (!$userObj->getEmailVerified()) { $userObj->setEmailVerified(1); $userObj->save(); } } } return $userId; } public function getRecoverPass() { return $this->recoverPass; } public function setRecoverPass($forceChange = false) { // let the same recover pass if it was 10 minutes ago if (!$this->isRecoverPassExpired($this->recoverPass) && empty($forceChange) && !empty($this->recoverPass) && !empty($recoverPass) && !empty($this->modified) && strtotime($this->modified) > strtotime("-10 minutes")) { return $this->recoverPass; } $this->recoverPass = $this->createRecoverPass(); return $this->recoverPass; } private function createRecoverPass($secondsValid = 600) { $json = new stdClass(); $json->valid = strtotime("+{$secondsValid} seconds"); return encryptString(json_encode($json)); } function checkRecoverPass($recoverPass) { if ($this->recoverPass === $recoverPass) { if (!$this->isRecoverPassExpired($recoverPass)) { _error_log('checkRecoverPass success: ' . $this->user . ' ' . getRealIpAddr()); return true; } } return false; } function isRecoverPassExpired($recoverPass) { $string = decryptString($recoverPass); if ($string) { $json = _json_decode($string); if (is_object($json)) { if (time() < $json->valid) { return false; } } } return true; } public static function canUpload($doNotCheckPlugins = false) { global $global, $config, $advancedCustomUser; if (Permissions::canModerateVideos()) { return true; } if (User::isAdmin()) { return true; } if (empty($doNotCheckPlugins) && !AVideoPlugin::userCanUpload(User::getId())) { return false; } if (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && !User::isVerified()) { return false; } if ($config->getAuthCanUploadVideos()) { return self::isLogged(); } if (self::isLogged() && !empty($_SESSION['user']['canUpload'])) { return true; } return self::isAdmin(); } public static function canViewChart() { global $global, $config; if (self::isLogged() && !empty($_SESSION['user']['canViewChart'])) { return true; } return self::isAdmin(); } public static function canCreateMeet() { global $global, $config; if (self::isLogged() && !empty($_SESSION['user']['canCreateMeet'])) { return true; } return self::isAdmin(); } public static function canComment() { global $global, $config, $advancedCustomUser; if (self::isAdmin()) { return true; } if (Permissions::canAdminComment()) { return true; } if ($config->getAuthCanComment()) { if (empty($advancedCustomUser->unverifiedEmailsCanNOTComment)) { return self::isLogged(); } else { return self::isVerified(); } } return false; } public static function canSeeCommentTextarea() { global $global, $config; if (!$config->getAuthCanComment()) { if (!self::isAdmin()) { return false; } } return true; } public function getUserGroups() { return $this->userGroups; } public function setUserGroups($userGroups) { if (is_array($userGroups)) { $this->userGroups = $userGroups; } } public function getIsAdmin() { return $this->isAdmin; } public function getStatus() { return $this->status; } /** * * @param type $user_id * text * label Default Primary Success Info Warning Danger */ public static function getTags($user_id) { $user = new User($user_id); $tags = array(); if ($user->getIsAdmin()) { $obj = new stdClass(); $obj->type = "info"; $obj->text = __("Admin"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "default"; $obj->text = __("Regular User"); $tags[] = $obj; } if ($user->getStatus() == "a") { $obj = new stdClass(); $obj->type = "success"; $obj->text = __("Active"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "danger"; $obj->text = __("Inactive"); $tags[] = $obj; } if ($user->getEmailVerified()) { $obj = new stdClass(); $obj->type = "success"; $obj->text = __("E-mail Verified"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "warning"; $obj->text = __("E-mail Not Verified"); $tags[] = $obj; } global $global; if (!empty($global['systemRootPath'])) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; } else { require_once 'userGroups.php'; } $groups = UserGroups::getUserGroups($user_id); foreach ($groups as $value) { $obj = new stdClass(); $obj->type = "warning"; $obj->text = $value['group_name']; $tags[] = $obj; } return $tags; } public function getBackgroundURL() { global $global; $this->backgroundURL = self::getBackgroundURLFromUserID($this->id); return $this->backgroundURL; } public static function getBackgroundURLFromUserID($users_id = 0) { if (empty($users_id)) { $users_id = User::getId(); } global $global; $backgroundURL = "videos/userPhoto/background{$users_id}.jpg"; if (!file_exists($global['systemRootPath'] . $backgroundURL)) { $backgroundURL = "videos/userPhoto/background{$users_id}.png"; } if (!file_exists($global['systemRootPath'] . $backgroundURL)) { $backgroundURL = "view/img/background.jpg"; } return $backgroundURL; } public function setBackgroundURL($backgroundURL) { $this->backgroundURL = strip_tags($backgroundURL); } public function getChannelName() { if (empty($this->channelName)) { $this->channelName = self::_recommendChannelName($this->channelName); $this->save(); } return $this->channelName; } public static function _getUserChannelName($users_id = 0) { global $global, $config; if (empty($users_id)) { $users_id = self::getId(); } $user = new User($users_id); if (empty($user)) { return false; } return $user->getChannelName(); } public function getEmailVerified() { return intval($this->emailVerified); } public static function validateChannelName($channelName) { return trim(preg_replace("/[^0-9A-Z_]/i", "", ucwords($channelName))); } /** * * @param type $channelName * @return boolean return true is is unique */ public function setChannelName($channelName) { $channelName = self::validateChannelName($channelName); $user = static::getChannelOwner($channelName); if (!empty($user)) { // if the channel name exists and it is not from this user, rename the channel name if (empty($this->id) || $user['id'] != $this->id) { return false; } } $this->channelName = xss_esc($channelName); return true; } public function setEmailVerified($emailVerified) { $this->emailVerified = (empty($emailVerified) || strtolower($emailVerified) === 'false') ? 0 : 1; } public static function getChannelLink($users_id = 0) { global $global; $name = self::_getChannelName($users_id); if (empty($name)) { return false; } $link = "{$global['webSiteRootURL']}channel/" . urlencode($name); return $link; } public static function getChannelLinkFromChannelName($channelName) { global $global; $link = "{$global['webSiteRootURL']}channel/" . urlencode($channelName); return $link; } public static function _getChannelName($users_id = 0) { global $global, $config; if (empty($users_id)) { $users_id = self::getId(); } $user = new User($users_id); if (empty($user)) { return false; } if (empty($user->getChannelName())) { $name = $user->getBdId(); } else { $name = $user->getChannelName(); } return $name; } public static function sendVerificationLink($users_id) { global $global, $advancedCustomUser; //Only send the verification email each 30 minutes if (!empty($_SESSION["sendVerificationLink"][$users_id]) && time() - $_SESSION["sendVerificationLink"][$users_id] > 1800) { _error_log("sendVerificationLink: Email already sent, we will wait 30 min {$users_id}"); return true; } $config = new Configuration(); $user = new User($users_id); $code = urlencode(static::createVerificationCode($users_id)); //Create a new PHPMailer instance if (!is_object($config)) { _error_log("sendVerificationLink: config is not a object " . json_encode($config)); return false; } $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); $email = $user->getEmail(); try { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); //$mail->SMTPDebug = 4; //Set who the message is to be sent from $mail->setFrom($contactEmail, $webSiteTitle); //Set who the message is to be sent to $mail->addAddress($email); //Set the subject line $mail->Subject = __('Please Verify Your E-mail ') . $webSiteTitle; $msg = sprintf(__("Hi %s"), $user->getName()); $msg .= "

" . __($advancedCustomUser->verificationMailTextLine1); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine2), $webSiteTitle); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine3), $webSiteTitle); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine4)); $msg .= "

" . " " . __("Verify") . ""; $mail->msgHTML($msg); $resp = $mail->send(); if (!$resp) { _error_log("sendVerificationLink Error Info: {$mail->ErrorInfo}"); } else { _session_start(); $_SESSION["sendVerificationLink"][$users_id] = time(); } return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } return false; } public static function verifyCode($code) { global $global; $obj = static::decodeVerificationCode($code); $salt = hash('sha256', $global['salt']); if ($salt !== $obj->salt) { return false; } $user = new User($obj->users_id); $recoverPass = $user->getRecoverPass(); if ($recoverPass == $obj->recoverPass) { $user->setEmailVerified(1); return $user->save(); } return false; } public static function createVerificationCode($users_id) { global $global; $obj = new stdClass(); $obj->users_id = $users_id; $obj->salt = hash('sha256', $global['salt']); $user = new User($users_id); $obj->recoverPass = $user->setRecoverPass(); $user->save(); return base64_encode(json_encode($obj)); } public static function decodeVerificationCode($code) { $obj = _json_decode(base64_decode($code)); return $obj; } public function getFirst_name() { return $this->first_name; } public function getLast_name() { return $this->last_name; } public function getAddress() { return $this->address; } public function getZip_code() { return $this->zip_code; } public function getCountry() { return $this->country; } public function getRegion() { return $this->region; } public function getCity() { return $this->city; } public function setFirst_name($first_name) { $this->first_name = $first_name; } public function setLast_name($last_name) { $this->last_name = $last_name; } public function setAddress($address) { $this->address = $address; } public function setZip_code($zip_code) { $this->zip_code = $zip_code; } public function setCountry($country) { $this->country = $country; } public function setRegion($region) { $this->region = $region; } public function setCity($city) { $this->city = $city; } public static function getDocumentImage($users_id) { $row = static::getBlob($users_id, User::$DOCUMENT_IMAGE_TYPE); if (!empty($row['blob'])) { return $row['blob']; } return false; } public static function saveDocumentImage($image, $users_id) { $row = static::saveBlob($image, $users_id, User::$DOCUMENT_IMAGE_TYPE); if (!empty($row['blob'])) { return $row['blob']; } return false; } public static function getBlob($users_id, $type) { global $global; $sql = "SELECT * FROM users_blob WHERE users_id = ? AND `type` = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "is", array($users_id, $type)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $result; } public static function saveBlob($blob, $users_id, $type) { global $global; $row = self::getBlob($users_id, $type); $null = null; if (!empty($row['id'])) { $sql = "UPDATE users_blob SET `blob` = ? , modified = now() WHERE id = ?"; $stmt = $global['mysqli']->prepare($sql); $stmt->bind_param('bi', $null, $row['id']); } else { $sql = "INSERT INTO users_blob (`blob`, users_id, `type`, modified, created) VALUES (?,?,?, now(), now())"; $stmt = $global['mysqli']->prepare($sql); $stmt->bind_param('bis', $null, $users_id, $type); } $stmt->send_long_data(0, $blob); return $stmt->execute(); } public static function deleteBlob($users_id, $type) { global $global; $row = self::getBlob($users_id, $type); if (!empty($row['id'])) { $sql = "DELETE FROM users_blob "; $sql .= " WHERE id = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($row['id'])); } _error_log("Id for table users_blob not defined for deletion"); return false; } public function getDonationLink() { return $this->donationLink; } public function getDonationLinkIfEnabled() { global $advancedCustomUser; if ($advancedCustomUser->allowDonationLink) { return $this->donationLink; } return false; } public function setDonationLink($donationLink) { $this->donationLink = $donationLink; } public static function donationLink() { if (self::isLogged()) { return $_SESSION['user']['donationLink']; } else { return false; } } public static function loginFromRequest() { inputToRequest(); if (!empty($_REQUEST['do_not_login'])) { return false; } - if(empty($_REQUEST['pass']) && !empty($_REQUEST['password'])){ + if (empty($_REQUEST['pass']) && !empty($_REQUEST['password'])) { $_REQUEST['pass'] = $_REQUEST['password']; } if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { $user = new User(0, $_REQUEST['user'], $_REQUEST['pass']); $user->login(false, !empty($_REQUEST['encodedPass'])); $_REQUEST['do_not_login'] = 1; } } public static function loginFromRequestToGet() { if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { $return = "user={$_REQUEST['user']}&pass={$_REQUEST['pass']}"; if (!empty($_REQUEST['encodedPass'])) { $return .= "&encodedPass=" . intval($_REQUEST['encodedPass']); } return $return; } return ""; } public static function getBlockUserButton($users_id) { $canBlock = self::userCanBlockUserWithReason($users_id); if (!$canBlock->result) { return ""; } return ReportVideo::buttonBlockUser($users_id); } public static function getActionBlockUserButton($users_id) { $canBlock = self::userCanBlockUserWithReason($users_id); if (!$canBlock->result) { return ""; } return ReportVideo::actionButtonBlockUser($users_id); } public static function userCanBlockUser($users_id, $ignoreIfIsAlreadyBLocked = false) { if (empty($users_id)) { return false; } if (!User::isLogged()) { return false; } if ($users_id == User::getId()) { return false; } if (empty($ignoreIfIsAlreadyBLocked)) { $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { return false; } } return true; } public static function userCanBlockUserWithReason($users_id, $ignoreIfIsAlreadyBLocked = false) { $obj = new stdClass(); $obj->result = false; $obj->msg = "Unkonw"; if (empty($users_id)) { $obj->msg = "Empty User ID"; return $obj; } if (!User::isLogged()) { $obj->msg = "You are not logged"; return $obj; } if ($users_id == User::getId()) { $obj->msg = "You cannot block your own video"; return $obj; } if (empty($ignoreIfIsAlreadyBLocked)) { $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { $obj->msg = "this user is already blocked"; return $obj; } } $obj->result = true; $obj->msg = "You can block"; return $obj; } public static function hasBlockedUser($reported_users_id, $users_id = 0) { if (empty($users_id)) { $users_id = User::getId(); } if (!self::userCanBlockUser($reported_users_id, true)) { return false; } $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (!empty($report)) { return ReportVideo::isBlocked($reported_users_id, $users_id); } else { return false; } } public function updateUserImages($params = array()) { $id = $this->id; $obj = new stdClass(); // Update Background Image if (isset($params['backgroundImg']) && $params['backgroundImg'] != '') { $background = url_get_contents($params['backgroundImg']); $ext = pathinfo(parse_url($params['backgroundImg'], PHP_URL_PATH), PATHINFO_EXTENSION); $allowed = array('jpg', 'jpeg', 'gif', 'png'); if (!in_array(strtolower($ext), $allowed)) { return "File extension error background Image, We allow only (" . implode(",", $allowed) . ")"; } $backgroundPath = "videos/userPhoto/tmp_background{$id}." . $ext; $oldfile = "videos/userPhoto/background{$id}.png"; $file = "videos/userPhoto/background{$id}.jpg"; if (!isset($global['systemRootPath'])) { $global['systemRootPath'] = '../../'; } $filePath = $global['systemRootPath'] . $backgroundPath; $updateBackground = file_put_contents($filePath, $background); convertImage($filePath, $global['systemRootPath'] . $file, 70); if (file_exists($filePath)) { unlink($filePath); } if (file_exists($oldfile)) { unlink($oldfile); } if ($updateBackground) { $obj->background = 'Background has been updated!'; } else { $obj->background = 'Error updating background.'; } $this->setBackgroundURL($file); } // Update Profile Image if (isset($params['profileImg']) && $params['profileImg'] != '') { $photo = url_get_contents($params['profileImg']); $photoPath = "videos/userPhoto/photo{$id}.png"; if (!isset($global['systemRootPath'])) { $global['systemRootPath'] = '../../'; } $filePath = $global['systemRootPath'] . $photoPath; if (file_exists($filePath)) { unlink($filePath); } $updateProfile = file_put_contents($filePath, $photo); if ($updateProfile) { $obj->profile = 'Profile has been updated!'; } else { $obj->profile = 'Error updating profile.'; } $this->setPhotoURL($photoPath); } $formats = "ssi"; $values[] = $this->photoURL; $values[] = $this->backgroundURL; $values[] = $this->id; $sql = "UPDATE users SET " . "photoURL = ?, backgroundURL = ?, " . " modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, $formats, $values); $obj->save = $insert_row; // create/update data for photoURL / backgroundURL return $obj; } function getExtra_info() { return $this->extra_info; } function setExtra_info($extra_info) { $this->extra_info = $extra_info; } static function saveExtraInfo($string, $users_id) { $sql = "UPDATE users SET " . "extra_info = ?, " . " modified = now() WHERE id = ?"; return sqlDAL::writeSql($sql, "si", array($string, $users_id)); } - - static function userGroupsMatch($user_groups, $users_id=0){ - if(empty($users_id)){ + + static function userGroupsMatch($user_groups, $users_id = 0) { + if (empty($users_id)) { $users_id = User::getId(); - } - if(empty($user_groups)){ + } + if (empty($user_groups)) { return true; } - if(empty($users_id)){ + if (empty($users_id)) { return false; } - if(!is_array($user_groups)){ + if (!is_array($user_groups)) { $user_groups = array($user_groups); - } + } $user_users_groups = UserGroups::getUserGroups($users_id); - if(empty($user_users_groups)){ + if (empty($user_users_groups)) { return false; } foreach ($user_users_groups as $value) { - if(in_array($value['id'], $user_groups)){ + if (in_array($value['id'], $user_groups)) { return true; } } return false; } } diff --git a/objects/userCreate.json.php b/objects/userCreate.json.php index be8c568eb..8dfe1490b 100644 --- a/objects/userCreate.json.php +++ b/objects/userCreate.json.php @@ -1,97 +1,97 @@ $value) { $_POST[$key] = $value; } } $obj = new stdClass(); if (empty($ignoreCaptcha)) { if (empty($_POST['captcha'])) { $obj->error = __("The captcha is empty"); die(json_encode($obj)); } require_once $global['systemRootPath'] . 'objects/captcha.php'; $valid = Captcha::validation($_POST['captcha']); if (!$valid) { $obj->error = __("The captcha is wrong"); die(json_encode($obj)); } } // check if user already exists $userCheck = new User(0, $_POST['user'], false); if (!empty($userCheck->getBdId())) { $obj->error = __("User already exists"); die(json_encode($obj)); } if (!empty($advancedCustomUser->forceLoginToBeTheEmail)) { $_POST['email'] = $_POST['user']; } $_POST['email'] = trim(@$_POST['email']); if (!empty($advancedCustomUser->emailMustBeUnique)) { if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { - $obj->error = __("You must specify an valid email"); + $obj->error = __("You must specify an valid email")." {$_POST['email']}"; die(json_encode($obj)); } $userFromEmail = User::getUserFromEmail($_POST['email']); if (!empty($userFromEmail)) { $obj->error = __("Email already exists"); die(json_encode($obj)); } } if (empty($_POST['user']) || empty($_POST['pass']) || empty($_POST['email']) || empty($_POST['name'])) { $obj->error = __("You must fill all fields"); die(json_encode($obj)); } if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { $obj->error = __("Invalid Email"); die(json_encode($obj)); } $user = new User(0); $user->setUser($_POST['user']); $user->setPassword($_POST['pass']); $user->setEmail($_POST['email']); $user->setName($_POST['name']); $user->setCanUpload($config->getAuthCanUploadVideos()); $users_id = $user->save(); if (!empty($users_id)) { $cu = AVideoPlugin::loadPluginIfEnabled('CustomizeUser'); if (!empty($cu)) { CustomizeUser::setCanShareVideosFromUser($users_id, true); } if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup UserGroups::updateUserGroups($users_id, array($advancedCustomUser->userDefaultUserGroup->value), true); } AVideoPlugin::onUserSignup($users_id); } echo '{"status":"' . $users_id . '"}'; diff --git a/objects/userUpdate.json.php b/objects/userUpdate.json.php index ff52dafa0..507d9873d 100644 --- a/objects/userUpdate.json.php +++ b/objects/userUpdate.json.php @@ -1,53 +1,53 @@ error = __("Is not logged"); die(json_encode($obj)); } $_REQUEST["do_not_login"]=1; require_once $global['systemRootPath'] . 'objects/user.php'; $user = new User(0); $user->loadSelfUser(); $user->setUser($_POST['user']); $user->setPassword($_POST['pass']); $user->setEmail($_POST['email']); $user->setName($_POST['name']); $user->setAbout($_POST['about']); $user->setAnalyticsCode($_POST['analyticsCode']); $user->setDonationLink($_POST['donationLink']); $unique = $user->setChannelName($_POST['channelName']); if (!$unique) { $obj->error = __("Channel name already exists"); die(json_encode($obj)); } if(empty($user->getBdId())){ $obj->error = __("User not found"); die(json_encode($obj)); } if (!empty($advancedCustomUser->emailMustBeUnique)) { if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { - $obj->error = __("You must specify an valid email"); + $obj->error = __("You must specify an valid email")." {$_POST['email']}"; die(json_encode($obj)); } $userFromEmail = User::getUserFromEmail($_POST['email']); if (!empty($userFromEmail) && $userFromEmail['id'] !== $user->getBdId()) { $obj->error = __("Email already exists"); die(json_encode($obj)); } } if (User::isAdmin() && !empty($_POST['status'])) { $user->setStatus($_POST['status']); } echo '{"status":"' . $user->save() . '"}'; User::updateSessionInfo(); diff --git a/objects/video_statistic.php b/objects/video_statistic.php index be1e01a0b..c51866438 100644 --- a/objects/video_statistic.php +++ b/objects/video_statistic.php @@ -1,553 +1,584 @@ You need to update your system"; return false; } */ if (empty($videos_id)) { die(__("You need a video to generate statistics")); } $userId = empty($_SESSION["user"]["id"]) ? "NULL" : $_SESSION["user"]["id"]; $lastVideoTime = 0; if (empty($currentTime)) { $lastStatistic = self::getLastStatistics($videos_id, $userId); if (empty($currentTime) && !empty($lastStatistic)) { $lastVideoTime = intval($lastStatistic['lastVideoTime']); } } else { $lastVideoTime = intval($currentTime); } $sql = "INSERT INTO videos_statistics " . "(`when`,ip, users_id, videos_id, lastVideoTime, created, modified, session_id) values " . "(now(),?," . $userId . ",?,{$lastVideoTime},now(),now(),'" . session_id() . "')"; $insert_row = sqlDAL::writeSql($sql, "si", array(getRealIpAddr(), $videos_id)); if (!empty($global['mysqli']->insert_id)) { return $global['mysqli']->insert_id; } else { die($sql . ' Save Video Statistics Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } - public static function updateStatistic($videos_id, $users_id, $lastVideoTime, $seconds_watching_video=0) { + public static function updateStatistic($videos_id, $users_id, $lastVideoTime, $seconds_watching_video = 0) { $lastStatistic = self::getLastStatistics($videos_id, $users_id); if (empty($lastStatistic)) { $vs = new VideoStatistic(0); $vs->setUsers_id($users_id); $vs->setVideos_id($videos_id); $vs->setWhen(date("Y-m-d h:i:s")); } else { $vs = new VideoStatistic($lastStatistic['id']); } $vs->setLastVideoTime($lastVideoTime); - - if(!empty($seconds_watching_video) && $seconds_watching_video > 0){ - $totalVideoWatched = $vs->getSeconds_watching_video()+$seconds_watching_video; - _error_log("updateStatistic: add more [$seconds_watching_video] to video [$videos_id] ". get_browser_name()); + + if (!empty($seconds_watching_video) && $seconds_watching_video > 0) { + $totalVideoWatched = $vs->getSeconds_watching_video() + $seconds_watching_video; + _error_log("updateStatistic: add more [$seconds_watching_video] to video [$videos_id] " . get_browser_name()); $vs->setSeconds_watching_video($totalVideoWatched); $v = new Video('', '', $videos_id); $v->addSecondsWatching($seconds_watching_video); - + //$totalVideoSeconds = timeToSeconds($hms); - //Video::addViewPercent(); - } - + $id = $vs->save(); /* - if(!empty($id)){ - Video::clearCache($videos_id); - } + if(!empty($id)){ + Video::clearCache($videos_id); + } */ return $id; } public function save() { if (empty($this->videos_id)) { return false; } $this->setSession_id(session_id()); if (empty($this->session_id) && empty($this->users_id)) { return false; } if (empty($this->users_id)) { $this->setUsers_id('null'); } - + $this->seconds_watching_video = intval($this->seconds_watching_video); - + return parent::save(); } public static function getLastStatistics($videos_id, $users_id = 0) { if (!empty($users_id)) { $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND users_id = ? ORDER BY modified DESC LIMIT 1 "; $res = sqlDAL::readSql($sql, 'ii', array($videos_id, $users_id), true); } else { $sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND session_id = ? ORDER BY modified DESC LIMIT 1 "; $res = sqlDAL::readSql($sql, 'is', array($videos_id, session_id()), true); } $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { return $result; } return false; } public static function getLastVideoTimeFromVideo($videos_id, $users_id) { $row = self::getLastStatistics($videos_id, $users_id); if (empty($row)) { return 0; } return intval($row['lastVideoTime']); } public static function getStatisticTotalViews($videos_id, $uniqueUsers = false, $startDate = "", $endDate = "") { global $global; if ($uniqueUsers) { $ast = "distinct(users_id)"; } else { $ast = "*"; } $sql = "SELECT count({$ast}) as total FROM videos_statistics WHERE 1=1 "; $formats = ""; $values = array(); if (!empty($videos_id)) { $sql .= " AND videos_id = ? "; $formats .= "i"; $values[] = $videos_id; } if (!empty($startDate)) { $sql .= " AND `when` >= ? "; $formats .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `when` <= ? "; $formats .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $formats, $values); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { //echo "
".$row['total']." --- ".$sql, "
"; return $result['total']; } return 0; } public static function getTotalLastDaysAsync($video_id, $numberOfDays) { global $global, $advancedCustom; $md5 = ("{$video_id}_{$numberOfDays}"); $path = getCacheDir() . "getTotalLastDaysAsync/"; make_path($path); $cacheFileName = "{$path}{$md5}"; if (!file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } $total = static::getTotalLastDays($video_id, $numberOfDays); file_put_contents($cacheFileName, json_encode($total)); return $total; } $return = _json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 60) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalLastDaysAsync.php' '$video_id' '$numberOfDays' '$cacheFileName'"); _error_log("getTotalLastDaysAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } public static function getTotalLastDays($video_id, $numberOfDays, $returnArray = array()) { if ($numberOfDays < 0) { return $returnArray; } $date = date("Y-m-d", strtotime("-{$numberOfDays} days")); $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . " 00:00:00", $date . " 23:59:59"); $numberOfDays--; return static::getTotalLastDays($video_id, $numberOfDays, $returnArray); } public static function getTotalToday($video_id, $hour = 0, $returnArray = array()) { if ($hour >= 24) { return $returnArray; } $date = date("Y-m-d {$hour}", time()); //echo $date;exit; $returnArray[] = static::getStatisticTotalViews($video_id, false, $date . ":00:00", $date . ":59:59"); $hour++; return static::getTotalToday($video_id, $hour, $returnArray); } public static function getTotalTodayAsync($video_id) { global $global, $advancedCustom; $cacheFileName = getCacheDir() . "getTotalTodayAsync_{$video_id}"; if (!file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } $total = static::getTotalToday($video_id); file_put_contents($cacheFileName, json_encode($total)); return $total; } $return = _json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 60) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalTodayAsync.php' '$video_id' '$cacheFileName'"); _error_log("getTotalTodayAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } public function getWhen() { return $this->when; } public function getIp() { return $this->ip; } public function getUsers_id() { return $this->users_id; } public function getVideos_id() { return $this->videos_id; } public function getLastVideoTime() { return $this->lastVideoTime; } public function setWhen($when) { $this->when = $when; } public function setIp($ip) { $this->ip = $ip; } public function setUsers_id($users_id) { $this->users_id = intval($users_id); if (empty($this->users_id)) { $this->users_id = 'null'; } } public function setVideos_id($videos_id) { $this->videos_id = intval($videos_id); } public function setLastVideoTime($lastVideoTime) { $this->lastVideoTime = intval($lastVideoTime); } public function getSession_id() { return $this->session_id; } public function setSession_id($session_id) { $this->session_id = $session_id; } public static function getChannelsWithMoreViews($daysLimit = 30) { global $global; $cacheName3 = "getChannelsWithMoreViews{$daysLimit}" . DIRECTORY_SEPARATOR . md5(json_encode(array($_GET, $_POST))); $cache = ObjectYPT::getCache($cacheName3, 3600); // 1 hour cache if (!empty($cache)) { - _error_log('getChannelsWithMoreViews cache found ' . $cacheName3); + _error_log('getChannelsWithMoreViews cache found ' . $cacheName3); return object_to_array($cache); } else { - _error_log('getChannelsWithMoreViews no cache found ' . $cacheName3); + _error_log('getChannelsWithMoreViews no cache found ' . $cacheName3); } // get unique videos ids from the requested timeframe $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE DATE(`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $channels = array(); $channelsPerUser = array(); $cacheName2 = "getChannelsWithMoreViews" . DIRECTORY_SEPARATOR . md5($sql); $cache2 = ObjectYPT::getCache($cacheName2, 3600); // 1 hour cache if (!empty($cache2)) { $channelsPerUser = object_to_array($cache2); } if (empty($channelsPerUser)) { $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { // get the channel owner from each of those videos foreach ($fullData as $row) { $users_id = Video::getOwner($row['videos_id']); if (empty($channelsPerUser[$users_id])) { $channelsPerUser[$users_id] = array(); } $channelsPerUser[$users_id][] = $row['videos_id']; } } $response = ObjectYPT::setCache($cacheName2, $channelsPerUser); } if (!empty($channelsPerUser)) { foreach ($channelsPerUser as $key => $value) { // count how many views each one has $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id IN (" . implode(",", $value) . ") AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); if (!empty($result2)) { $channels[$key]['users_id'] = $key; $channels[$key]['total'] = intval($result2['total']); } } // return more first usort($channels, function ($a, $b) { return $a['total'] - $b['total']; }); } $response = ObjectYPT::setCache($cacheName3, $channels); _error_log('getChannelsWithMoreViews cache saved [' . json_encode($response) . '] ' . $cacheName3); return $channels; } public static function getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly, $daysLimit = 30) { global $global; // get unique videos ids from the requested timeframe $sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics s " . " LEFT JOIN videos v ON v.id = videos_id " . " WHERE DATE(s.`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $sql .= " AND v.users_id = '{$user['id']}' "; } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; } $sql .= static::getSqlLimit(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $channels = array(); $videos = array(); if ($res != false) { foreach ($fullData as $key => $value) { // count how many views each one has $sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id = {$value['videos_id']} AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); if (!empty($result2)) { $video = Video::getVideo($value['videos_id'], $status, false, false, $suggestedOnly, $showUnlisted, false, $showOnlyLoggedUserVideos); if (empty($video)) { continue; } $video['total'] = $result2['total']; $videos[] = $video; } } } // return more first usort($videos, function ($a, $b) { return $a['total'] - $b['total']; }); return $videos; } public static function getUsersIDFromChannelsWithMoreViews($daysLimit = 30) { $channels = self::getChannelsWithMoreViews($daysLimit); $users_id = array(); foreach ($channels as $value) { $users_id[] = $value['users_id']; } return $users_id; } public static function getChannelsTotalViews($users_id, $daysLimit = 30) { global $global; $cacheName = "getChannelsTotalViews($users_id, $daysLimit)"; $cache = ObjectYPT::getCache($cacheName, 3600); // 1 hour cache if (!empty($cache)) { return object_to_array($cache); } $users_id = intval($users_id); // count how many views each one has $sql2 = "SELECT count(s.id) as total FROM videos_statistics s " . " LEFT JOIN videos v ON v.id = videos_id WHERE v.users_id = $users_id " . " AND DATE(s.`when`) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); $result = 0; if (!empty($result2)) { $result = intval($result2['total']); } - ObjectYPT::setCache($cacheName, $result); + ObjectYPT::setCache($cacheName, $result); return 0; } - - + public static function getTotalStatisticsRecords() { global $global; $sql2 = "SELECT count(s.id) as total FROM videos_statistics s "; $res2 = sqlDAL::readSql($sql2); $result2 = sqlDAL::fetchAssoc($res2); sqlDAL::close($res2); $result = 0; if (!empty($result2)) { return intval($result2['total']); } - ObjectYPT::setCache($cacheName, $result); + ObjectYPT::setCache($cacheName, $result); return 0; } - + public static function deleteOldStatistics($days) { global $global; $days = intval($days); if (!empty($days)) { $sql = "DELETE FROM " . static::getTableName() . " "; $sql .= " WHERE created < DATE_SUB(NOW(), INTERVAL ? DAY) "; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($days)); } _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); return false; } - + function getSeconds_watching_video() { return intval($this->seconds_watching_video); } function setSeconds_watching_video($seconds_watching_video) { $this->seconds_watching_video = intval($seconds_watching_video); } - - + + function getJson() { + return $this->json; + } + + function setJson($json) { + if(!is_string($json)){ + $json = _json_encode($json); + } + $this->json = $json; + } public static function getAllFromVideos_id($videos_id) { global $global; if (!static::isTableInstalled()) { return false; } - + $videos_id = intval($videos_id); - - if(empty($videos_id)){ + + if (empty($videos_id)) { return false; } - + $sql = "SELECT * FROM " . static::getTableName() . " WHERE videos_id=$videos_id "; $sql .= self::getSqlFromPost(); //echo $sql;//exit; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { + + $isPluginEnabled = AVideoPlugin::isEnabledByName('User_Location'); + foreach ($fullData as $row) { + $row['users'] = User::getNameIdentificationById($row['users_id']); + $row['when_human'] = humanTimingAgo($row['when']); + $row['seconds_watching_video_human'] = seconds2human($row['seconds_watching_video']); + if ($isPluginEnabled) { + + $json = _json_decode($row['json']); + if (empty($json)) { + $json = new stdClass(); + } + if (empty($json->location)) { + $json->location = User_Location::getLocationFromIP($row['ip']); + $vs = new VideoStatistic($row['id']); + $vs->setJson($json); + $vs->save(); + } + + $row['location'] = $json->location; + $row['location_name'] = "{$json->location->country_name}, {$json->location->city_name}"; + } else { + $row['location_name'] = $row['location'] = ''; + } $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } - + public static function getTotalFromVideos_id($videos_id) { global $global; if (!static::isTableInstalled()) { return false; } - + $videos_id = intval($videos_id); - - if(empty($videos_id)){ + + if (empty($videos_id)) { return false; } - + $sql = "SELECT count(id) as total FROM " . static::getTableName() . " WHERE videos_id=$videos_id "; $sql .= self::getSqlSearchFromPost(); - + //echo $sql;//exit; $res = sqlDAL::readSql($sql); $result = sqlDAL::fetchAssoc($res); if (!empty($result)) { return intval($result['total']); - } + } return 0; } } diff --git a/plugin/User_Location/User_Location.php b/plugin/User_Location/User_Location.php index 3286ed11e..758af37c4 100644 --- a/plugin/User_Location/User_Location.php +++ b/plugin/User_Location/User_Location.php @@ -1,102 +1,106 @@ This site or product includes IP2Location LITE data available from http://www.ip2location.com."; $ret .= "
Before use this plugin unzip the install.zip file and install the IPs tables"; $ret .= "
cd {$global['systemRootPath']}plugin/User_Location/install && unzip install.zip
"; if(!ObjectYPT::isTableInstalled("ip2location_db1_ipv6")){ $ret .= "
For IPV6 support unzip the ip2location_db1_ipv6.zip file and install the IPs tables"; $ret .= "
cd {$global['systemRootPath']}plugin/User_Location/install && unzip ip2location_db1_ipv6.zip && mysql -u root -p {$mysqlDatabase} <  {$global['systemRootPath']}plugin/User_Location/install/ip2location_db1_ipv6.sql 
"; } return $ret; } public function getName() { return "User_Location"; } public function getUUID() { return "45432a78-d0c6-47f3-8ac4-8fd05f507386"; } public function getPluginVersion() { return "1.0"; } public function getEmptyDataObject() { $obj = new stdClass(); $obj->autoChangeLanguage = true; return $obj; } static function getSessionLocation(){ $ip = getRealIpAddr(); if(!empty($_SESSION['User_Location'][$ip]['country_name'])){ if ($_SESSION['User_Location'][$ip]['country_name'] == "United States of America") { $_SESSION['User_Location'][$ip]['country_name'] = "United States"; } return $_SESSION['User_Location'][$ip]; } return false; } static function setSessionLocation($value){ $ip = getRealIpAddr(); $_SESSION['User_Location'][$ip] = $value; //_error_log("User_Location: $ip ". json_encode($_SESSION['User_Location'][$ip])); } - static function getThisUserLocation() { + static function getThisUserLocation() { $location = self::getSessionLocation(); if(!empty($location['country_code'])){ return $location; } - return IP2Location::getLocation(getRealIpAddr()); + return self::getLocationFromIP(getRealIpAddr()); + } + + static function getLocationFromIP($ip) { + return IP2Location::getLocation($ip); } public function getStart() { global $global, $config; $obj = $this->getDataObject(); $User_Location = self::getThisUserLocation(); if (session_status() == PHP_SESSION_NONE) { session_start(); } if($obj->autoChangeLanguage){ $location = self::getSessionLocation(); if(empty($location) && !empty($User_Location['country_code'])){ $_SESSION['language'] = strtolower($User_Location['country_code']); $file = "{$global['systemRootPath']}locale/{$_SESSION['language']}.php"; if(file_exists($file)){ include_once $file; }else{ $_SESSION['language'] = $config->getLanguage(); } } } $global['User_Location'] = $User_Location; self::setSessionLocation($global['User_Location']); return false; } public function getPluginMenu() { global $global; $filename = $global['systemRootPath'] . 'plugin/User_Location/pluginMenu.html'; return file_get_contents($filename); } } diff --git a/updatedb/updateDb.v11.3.sql b/updatedb/updateDb.v11.3.sql new file mode 100644 index 000000000..6218866ef --- /dev/null +++ b/updatedb/updateDb.v11.3.sql @@ -0,0 +1,12 @@ +SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; +SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; +SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; + +ALTER TABLE `videos_statistics` +ADD COLUMN `json` TEXT NULL DEFAULT NULL ; + +SET SQL_MODE=@OLD_SQL_MODE; +SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; +SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; + +UPDATE configurations SET version = '11.3', modified = now() WHERE id = 1; \ No newline at end of file diff --git a/view/js/script.js b/view/js/script.js index 07c5fd08a..4ac51378d 100644 --- a/view/js/script.js +++ b/view/js/script.js @@ -1,1825 +1,1847 @@ var modal; var player; var floatLeft = ""; var floatTop = ""; var floatWidth = ""; var floatHeight = ""; var changingVideoFloat = 0; var floatClosed = 0; var fullDuration = 0; var isPlayingAd = false; var mainVideoHeight = 0; var mouseX; var mouseY; var videoContainerDragged = false; var youTubeMenuIsOpened = false; var userIsControling = false; var _serverTime; var _serverDBTime; var _serverTimeString; var _serverDBTimeString; let deferredPrompt; var playerCurrentTime; var mediaId; $(document).mousemove(function (e) { mouseX = e.pageX; mouseY = e.pageY; }); String.prototype.stripAccents = function () { var returnvar = this.replace(/[áàâãªä]/g, 'a'); returnvar = returnvar.replace(/[ÁÀÂÃÄ]/g, 'A'); returnvar = returnvar.replace(/[ÍÌÎÏ]/g, 'I'); returnvar = returnvar.replace(/[íìîï]/g, 'i'); returnvar = returnvar.replace(/[éèêë]/g, 'e'); returnvar = returnvar.replace(/[ÉÈÊË]/g, 'E'); returnvar = returnvar.replace(/[óòôõºö]/g, 'o'); returnvar = returnvar.replace(/[ÓÒÔÕÖ]/g, 'O'); returnvar = returnvar.replace(/[úùûü]/g, 'u'); returnvar = returnvar.replace(/[ÚÙÛÜ]/g, 'U'); returnvar = returnvar.replace(/ç/g, 'c'); returnvar = returnvar.replace(/Ç/g, 'C'); returnvar = returnvar.replace(/ñ/g, 'n'); returnvar = returnvar.replace(/Ñ/g, 'N'); returnvar = returnvar.replace(/–/g, '-'); returnvar = returnvar.replace(/[’‘‹›‚]/g, ' '); returnvar = returnvar.replace(/[“”«»„]/g, ' '); returnvar = returnvar.replace(/ /g, ' '); returnvar = returnvar.replace(/Є/g, 'YE'); returnvar = returnvar.replace(/І/g, 'I'); returnvar = returnvar.replace(/Ѓ/g, 'G'); returnvar = returnvar.replace(/і/g, 'i'); returnvar = returnvar.replace(/№/g, '#'); returnvar = returnvar.replace(/є/g, 'ye'); returnvar = returnvar.replace(/ѓ/g, 'g'); returnvar = returnvar.replace(/А/g, 'A'); returnvar = returnvar.replace(/Б/g, 'B'); returnvar = returnvar.replace(/В/g, 'V'); returnvar = returnvar.replace(/Г/g, 'G'); returnvar = returnvar.replace(/Д/g, 'D'); returnvar = returnvar.replace(/Е/g, 'E'); returnvar = returnvar.replace(/Ё/g, 'YO'); returnvar = returnvar.replace(/Ж/g, 'ZH'); returnvar = returnvar.replace(/З/g, 'Z'); returnvar = returnvar.replace(/И/g, 'I'); returnvar = returnvar.replace(/Й/g, 'J'); returnvar = returnvar.replace(/К/g, 'K'); returnvar = returnvar.replace(/Л/g, 'L'); returnvar = returnvar.replace(/М/g, 'M'); returnvar = returnvar.replace(/Н/g, 'N'); returnvar = returnvar.replace(/О/g, 'O'); returnvar = returnvar.replace(/П/g, 'P'); returnvar = returnvar.replace(/Р/g, 'R'); returnvar = returnvar.replace(/С/g, 'S'); returnvar = returnvar.replace(/Т/g, 'T'); returnvar = returnvar.replace(/У/g, 'U'); returnvar = returnvar.replace(/Ф/g, 'F'); returnvar = returnvar.replace(/Х/g, 'H'); returnvar = returnvar.replace(/Ц/g, 'C'); returnvar = returnvar.replace(/Ч/g, 'CH'); returnvar = returnvar.replace(/Ш/g, 'SH'); returnvar = returnvar.replace(/Щ/g, 'SHH'); returnvar = returnvar.replace(/Ъ/g, ''); returnvar = returnvar.replace(/Ы/g, 'Y'); returnvar = returnvar.replace(/Ь/g, ''); returnvar = returnvar.replace(/Э/g, 'E'); returnvar = returnvar.replace(/Ю/g, 'YU'); returnvar = returnvar.replace(/Я/g, 'YA'); returnvar = returnvar.replace(/а/g, 'a'); returnvar = returnvar.replace(/б/g, 'b'); returnvar = returnvar.replace(/в/g, 'v'); returnvar = returnvar.replace(/г/g, 'g'); returnvar = returnvar.replace(/д/g, 'd'); returnvar = returnvar.replace(/е/g, 'e'); returnvar = returnvar.replace(/ё/g, 'yo'); returnvar = returnvar.replace(/ж/g, 'zh'); returnvar = returnvar.replace(/з/g, 'z'); returnvar = returnvar.replace(/и/g, 'i'); returnvar = returnvar.replace(/й/g, 'j'); returnvar = returnvar.replace(/к/g, 'k'); returnvar = returnvar.replace(/л/g, 'l'); returnvar = returnvar.replace(/м/g, 'm'); returnvar = returnvar.replace(/н/g, 'n'); returnvar = returnvar.replace(/о/g, 'o'); returnvar = returnvar.replace(/п/g, 'p'); returnvar = returnvar.replace(/р/g, 'r'); returnvar = returnvar.replace(/с/g, 's'); returnvar = returnvar.replace(/т/g, 't'); returnvar = returnvar.replace(/у/g, 'u'); returnvar = returnvar.replace(/ф/g, 'f'); returnvar = returnvar.replace(/х/g, 'h'); returnvar = returnvar.replace(/ц/g, 'c'); returnvar = returnvar.replace(/ч/g, 'ch'); returnvar = returnvar.replace(/ш/g, 'sh'); returnvar = returnvar.replace(/щ/g, 'shh'); returnvar = returnvar.replace(/ъ/g, ''); returnvar = returnvar.replace(/ы/g, 'y'); returnvar = returnvar.replace(/ь/g, ''); returnvar = returnvar.replace(/э/g, 'e'); returnvar = returnvar.replace(/ю/g, 'yu'); returnvar = returnvar.replace(/я/g, 'ya'); returnvar = returnvar.replace(/—/g, '-'); returnvar = returnvar.replace(/«/g, ''); returnvar = returnvar.replace(/»/g, ''); returnvar = returnvar.replace(/…/g, ''); return returnvar; }; function clean_name(str) { str = str.stripAccents().toLowerCase(); return str.replace(/[!#$&'()*+,/:;=?@[\] ]+/g, "-"); } function lazyImage() { try { if ($(".thumbsJPG").length) { $('.thumbsJPG').lazy({ effect: 'fadeIn', visibleOnly: true, // called after an element was successfully handled afterLoad: function (element) { element.addClass('gifNotLoaded'); element.removeClass('blur'); element.mouseover(function () { if ($(this).hasClass('gifNotLoaded')) { var element = $(this); element.removeClass('gifNotLoaded'); var gif = element.parent().find('.thumbsGIF'); gif.lazy({ effect: 'fadeIn' }); gif.height(element.height()); gif.width(element.width()); //console.log('lazyImage', gif); } $("#log").append("
Handler for .mouseover() called.
"); }); } }); mouseEffect(); } } catch (e) { } } lazyImage(); var pleaseWaitIsINUse = false; var pauseIfIsPlayinAdsInterval; var seconds_watching_video = 0; var _startCountPlayingTime; function setPlayerListners() { if (typeof player !== 'undefined') { player.on('pause', function () { clearTimeout(promisePlayTimeout); console.log("setPlayerListners: pause"); //userIsControling = true; clearInterval(pauseIfIsPlayinAdsInterval); clearInterval(_startCountPlayingTime); }); player.on('play', function () { isTryingToPlay = false; clearTimeout(promisePlayTimeout); console.log("setPlayerListners: play"); //userIsControling = true; pauseIfIsPlayinAdsInterval = setInterval(function () { pauseIfIsPlayinAds(); }, 500); clearInterval(_startCountPlayingTime); _startCountPlayingTime = setInterval(function () { seconds_watching_video++; }, 1000); }); $("#mainVideo .vjs-mute-control").click(function () { Cookies.set('muted', player.muted(), { path: '/', expires: 365 }); }); } else { setTimeout(function () { setPlayerListners(); }, 2000); } } function removeTracks() { var oldTracks = player.remoteTextTracks(); var i = oldTracks.length; while (i--) { player.removeRemoteTextTrack(oldTracks[i]); } } function changeVideoSrc(vid_obj, source) { var srcs = []; removeTracks(); for (i = 0; i < source.length; i++) { if (source[i].type) { console.log(source[i].type); if (source[i].type === "application/x-mpegURL") { // it is HLS cancel it return false; } srcs.push(source[i]); } else if (source[i].srclang) { player.addRemoteTextTrack(source[i]); } } vid_obj.src(srcs); setTimeout(function () { changeVideoSrcLoad(); }, 1000); return true; } function changeVideoSrcLoad() { console.log("changeVideoSrcLoad: Try to load player"); player.load(); player.ready(function () { console.log("changeVideoSrcLoad: Player ready"); var err = this.error(); if (err && err.code) { console.log("changeVideoSrcLoad: Load player Error"); setTimeout(function () { changeVideoSrcLoad(); }, 1000); } else { console.log("changeVideoSrcLoad: Load player Success, Play"); setTimeout(function () { player.load(); console.log("changeVideoSrcLoad: Trying to play"); player.play(); }, 1000); } }); } var _reloadAdsTimeout; var isReloadingAds = false; function reloadAds() { if (isReloadingAds) { return false; } isReloadingAds = true; setTimeout(function () { isReloadingAds = false; }, 500); clearTimeout(_reloadAdsTimeout); console.log('reloadAds '); if (playerIsReady() && player.ima) { try { console.log('reloadAds player.ima.getAdsManager()', player.ima.getAdsManager()); if (player.ima.getAdsManager()) { player.ima.requestAds(); } player.ima.changeAdTag(null); player.ima.setContentWithAdTag(null, _adTagUrl, false); player.ima.changeAdTag(_adTagUrl); setTimeout(function () { player.ima.requestAds(); console.log('reloadAds done'); }, 2000); player.ima.requestAds(); } catch (e) { console.log('reloadAds ERROR', e.message); } } else { _reloadAdsTimeout = setTimeout(function () { reloadAds(); }, 200); } } /** * * @param {String} str 00:00:00 * @returns {int} int of seconds */ function strToSeconds(str) { var partsOfStr = str.split(':'); var seconds = parseInt(partsOfStr[2]); seconds += parseInt(partsOfStr[1]) * 60; seconds += parseInt(partsOfStr[0]) * 60 * 60; return seconds; } /** * * @param {int} seconds * @param {int} level 3 = 00:00:00 2 = 00:00 1 = 00 * @returns {String} 00:00:00 */ function secondsToStr(seconds, level) { var hours = parseInt(seconds / (60 * 60)); var minutes = parseInt(seconds / (60)); seconds = parseInt(seconds % (60)); hours = hours > 9 ? hours : "0" + hours; minutes = minutes > 9 ? minutes : "0" + minutes; seconds = seconds > 9 ? seconds : "0" + seconds; switch (level) { case 3: return hours + ":" + minutes + ":" + seconds; break; case 2: return minutes + ":" + seconds; break; case 1: return seconds; break; default: return hours + ":" + minutes + ":" + seconds; } } function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function isEmailValid(email) { return validateEmail(email); } function subscribe(email, user_id) { modal.showPleaseWait(); $.ajax({ url: webSiteRootURL + 'objects/subscribe.json.php', method: 'POST', data: { 'email': email, 'user_id': user_id }, success: function (response) { var totalElement = $('.notificationButton' + user_id + ' .badge'); if (response.subscribe == "i") { $('.notificationButton' + user_id).removeClass("subscribed"); totalElement.text(parseInt(totalElement.first().text()) - 1); } else { $('.notificationButton' + user_id).addClass("subscribed"); totalElement.text(parseInt(totalElement.first().text()) + 1); } $('#popover-content #subscribeEmail').val(email); $('.subscribeButton' + user_id).popover('hide'); modal.hidePleaseWait(); } }); } function toogleNotify(user_id) { email = $('#subscribeEmail' + user_id).val(); subscribeNotify(email, user_id); } function subscribeNotify(email, user_id) { modal.showPleaseWait(); $.ajax({ url: webSiteRootURL + 'objects/subscribeNotify.json.php', method: 'POST', data: { 'email': email, 'user_id': user_id }, success: function (response) { if (response.notify) { $('.notificationButton' + user_id).addClass("notify"); } else { $('.notificationButton' + user_id).removeClass("notify"); } modal.hidePleaseWait(); } }); } function mouseEffect() { $(".thumbsImage").on("mouseenter", function () { var gif = $(this).find(".thumbsGIF"); var jpg = $(this).find(".thumbsJPG"); try { gif.lazy({effect: 'fadeIn'}); setTimeout(function () { gif.height(jpg.height()); gif.width(jpg.width()); }, 100); } catch (e) { } gif.height(jpg.height()); gif.width(jpg.width()); gif.stop(true, true).fadeIn(); }); $(".thumbsImage").on("mouseleave", function () { $(this).find(".thumbsGIF").stop(true, true).fadeOut(); }); } function isMobile() { var check = false; (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true })(navigator.userAgent || navigator.vendor || window.opera); return check; } var last_videos_id = 0; var last_currentTime = -1; var videoViewAdded = false; var addViewBeaconTimeout; function addView(videos_id, currentTime) { if (last_videos_id == videos_id && last_currentTime == currentTime) { return false; } if (currentTime > 5 && currentTime % 30 !== 0) { // only update each 30 seconds return false; } if (videoViewAdded && videoViewAdded == videos_id) { clearTimeout(addViewBeaconTimeout); addViewBeaconTimeout = setTimeout(function () { addViewBeacon(); } // update the time watched , 500); } else { videoViewAdded = videos_id; last_videos_id = videos_id; last_currentTime = currentTime; _addView(videos_id, currentTime); } return true; } function addViewBeacon() { console.log('addViewBeacon'); if (typeof mediaId !== 'undefined' && typeof playerCurrentTime !== 'undefined' && typeof seconds_watching_video !== 'undefined') { if (seconds_watching_video <= 0) { console.log('addViewBeacon seconds_watching_video <= 0 ', seconds_watching_video); return false; } var url = webSiteRootURL + 'objects/videoAddViewCount.json.php?PHPSESSID=' + PHPSESSID; url = addGetParam(url, 'id', mediaId); url = addGetParam(url, 'currentTime', playerCurrentTime); url = addGetParam(url, 'seconds_watching_video', seconds_watching_video); console.log('addViewBeacon will be sent', mediaId, playerCurrentTime, seconds_watching_video, beacon); seconds_watching_video = 0; var beacon = new Image(); beacon.src = url; } else { if (typeof mediaId !== 'undefined') { console.log('addViewBeacon mediaId is undefined'); } if (typeof playerCurrentTime !== 'undefined') { console.log('addViewBeacon playerCurrentTime is undefined'); } if (typeof seconds_watching_video !== 'undefined') { console.log('addViewBeacon seconds_watching_video is undefined'); } } return ''; } function _addView(videos_id, currentTime) { $.ajax({ url: webSiteRootURL + 'objects/videoAddViewCount.json.php?PHPSESSID=' + PHPSESSID, method: 'POST', data: { 'id': videos_id, 'currentTime': currentTime }, success: function (response) { $('.view-count' + videos_id).text(response.countHTML); } }); } +var _addViewAsyncSent = false; +function _addViewAsync() { + if(_addViewAsyncSent){ + return false; + } + _addViewAsyncSent = true; + $.ajax({ + url: webSiteRootURL + 'objects/videoAddViewCount.json.php?PHPSESSID=' + PHPSESSID, + method: 'POST', + data: { + 'id': mediaId, + 'currentTime': playerCurrentTime, + 'seconds_watching_video': seconds_watching_video + }, + async: false, + success: function (response) { + console.log('_addViewAsync', response); + setTimeout(function(){_addViewAsyncSent=false;},2000); + } + }); +} + function getPlayerButtonIndex(name) { var children = player.getChild('controlBar').children(); for (i = 0; i < children.length; i++) { if (children[i].name_ === name) { return i; } } return children.length; } function copyToClipboard(text) { $('body').append(''); $('#elementToCopyAvideo').css({'top': mouseY, 'left': 0}).fadeIn('slow'); $('#elementToCopyAvideo').val(text); $('#elementToCopyAvideo').focus(); $('#elementToCopyAvideo').select(); document.execCommand('copy'); $('#elementToCopyAvideo').remove(); $.toast("Copied to Clipboard"); } function nl2br(str, is_xhtml) { if (typeof str === 'undefined' || str === null) { return ''; } var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '
' : '
'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); } function inIframe() { try { return window.self !== window.top; } catch (e) { return true; } } function playerIsReady() { return (typeof player !== 'undefined' && player.isReady_); } var promisePlaytry = 20; var promisePlayTimeoutTime = 500; var promisePlayTimeout; var promisePlay; var browserPreventShowed = false; var playerPlayTimeout; var isTryingToPlay = false; function playerPlay(currentTime) { isTryingToPlay = true; clearTimeout(playerPlayTimeout); if (playerIsPlayingAds()) { return false; } if (currentTime) { console.log("playerPlay time:", currentTime); } if (!playerIsReady()) { playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); return false; } if (userIsControling) { // stops here if the user already clicked on play or pause console.log("playerPlay: userIsControling"); return true; } if (promisePlaytry <= 0) { console.log("playerPlay: promisePlaytry <= 0"); if (!browserPreventShowed) { browserPreventShowed = true; $.toast("Your browser prevent autoplay"); } return false; } promisePlaytry--; if (typeof player !== 'undefined') { if (currentTime) { setCurrentTime(currentTime); } try { console.log("playerPlay: Trying to play", player); promisePlay = player.play(); if (promisePlay !== undefined) { tryToPlay(currentTime); console.log("playerPlay: promise found", currentTime); promisePlay.then(function () { console.log("playerPlay: Autoplay started", currentTime); userIsControling = true; if (player.paused()) { console.log("The video still paused, trying to mute and play"); if (promisePlaytry <= 10) { console.log("playerPlay: (" + promisePlaytry + ") The video still paused, trying to mute and play"); tryToPlayMuted(currentTime); } else { console.log("playerPlay: (" + promisePlaytry + ") The video still paused, trying to play again"); tryToPlay(currentTime); } } else { //player.muted(false); if (player.muted() && !inIframe()) { showUnmutePopup(); } } }).catch(function (error) { if (player.networkState() === 3) { promisePlaytry = 20; console.log("playerPlay: Network error detected, trying again"); player.src(player.currentSources()); userIsControling = false; tryToPlay(currentTime); } else { if (promisePlaytry <= 10) { console.log("playerPlay: (" + promisePlaytry + ") Autoplay was prevented, trying to mute and play ***"); tryToPlayMuted(currentTime); } else { console.log("playerPlay: (" + promisePlaytry + ") Autoplay was prevented, trying to play again"); tryToPlay(currentTime); } } }); } else { tryToPlay(currentTime); } } catch (e) { console.log("playerPlay: We could not autoplay, trying again in 1 second"); tryToPlay(currentTime); } } else { console.log("playerPlay: Player is Undefined"); } } function showUnmutePopup() { var donotShowUnmuteAgain = Cookies.get('donotShowUnmuteAgain'); if (!donotShowUnmuteAgain) { var span = document.createElement("span"); span.innerHTML = "Would you like to unmute it?
"; swal({ title: "Your Media is Muted", icon: "warning", content: span, dangerMode: true, buttons: { cancel: "Cancel", unmute: true, donotShowUnmuteAgain: { text: "Don't show again", value: "donotShowUnmuteAgain", className: "btn-danger", }, } }).then(function (value) { switch (value) { case "unmute": player.muted(false); break; case "donotShowUnmuteAgain": Cookies.set('donotShowUnmuteAgain', true, { path: '/', expires: 365 }); break; } }); } showMuteTooltip(); setTimeout(function () { $("#allowAutoplay").load(webSiteRootURL + "plugin/PlayerSkins/allowAutoplay/"); player.userActive(true); }, 500); } function tryToPlay(currentTime) { clearTimeout(promisePlayTimeout); promisePlayTimeout = setTimeout(function () { if (player.paused()) { playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } }, promisePlayTimeoutTime); } function tryToPlayMuted(currentTime) { muteInCookieAllow(); return tryToPlay(currentTime); } function muteIfNotAudio() { if (!player.isAudio()) { console.log("muteIfNotAudio: We will mute this video"); player.muted(true); return true; } console.log("muteIfNotAudio: We will not mute an audio"); return false; } function muteInCookieAllow() { var mute = Cookies.get('muted'); if (isALiveContent() || typeof mute === 'undefined' || (mute && mute !== "false")) { console.log("muteInCookieAllow: said yes"); return muteIfNotAudio(); } console.log("muteInCookieAllow: said no"); return false; } function playMuted(currentTime) { muteInCookieAllow(); playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } function showMuteTooltip() { if ($("#mainVideo .vjs-volume-panel").length) { if (!$("#mainVideo .vjs-volume-panel").is(":visible")) { setTimeout(function () { showMuteTooltip(); }, 500); return false; } $("#mainVideo .vjs-volume-panel").attr("data-toggle", "tooltip"); $("#mainVideo .vjs-volume-panel").attr("data-placement", "top"); $("#mainVideo .vjs-volume-panel").attr("title", "Click to activate the sound"); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip({container: '.vjs-control-bar'}); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('show'); $("#mainVideo .vjs-volume-panel").click(function () { console.log("remove unmute tooltip"); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('hide'); $("#mainVideo .vjs-volume-panel").removeAttr("data-toggle"); $("#mainVideo .vjs-volume-panel").removeAttr("data-placement"); $("#mainVideo .vjs-volume-panel").removeAttr("title"); $("#mainVideo .vjs-volume-panel").removeData('tooltip').unbind().next('div.tooltip').remove(); }); } player.userActive(true); setTimeout(function () { player.userActive(true); }, 1000); setTimeout(function () { player.userActive(true); }, 1500); setTimeout(function () { $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('hide'); }, 5000); } function playerPlayIfAutoPlay(currentTime) { if (isWebRTC()) { return false; } if (isAutoplayEnabled()) { playerPlayTimeout = setTimeout(function () { console.log('playerPlayIfAutoPlay true', currentTime); playerPlay(currentTime); }, 200); return true; } console.log('playerPlayIfAutoPlay false', currentTime); if (currentTime) { setCurrentTime(currentTime); } //$.toast("Autoplay disabled"); return false; } function playNext(url) { if (!player.paused()) { return false; } if (playerIsPlayingAds()) { setTimeout(function () { playNext(url); }, 1000); } else if (isPlayNextEnabled()) { modal.showPleaseWait(); if (typeof autoPlayAjax == 'undefined' || !autoPlayAjax) { console.log("playNext changing location " + url); document.location = url; } else { console.log("playNext ajax"); $.ajax({ url: webSiteRootURL + 'view/infoFromURL.php?url=' + encodeURI(url), success: function (response) { console.log(response); if (!response || response.error) { console.log("playNext ajax fail"); if (response.url) { //document.location = response.url; } } else { console.log("playNext ajax success"); $('topInfo').hide(); playNextURL = (typeof isEmbed !== 'undefined' && isEmbed) ? response.nextURLEmbed : response.nextURL; console.log("New playNextURL", playNextURL); var cSource = false; try { cSource = changeVideoSrc(player, response.sources); } catch (e) { console.log('changeVideoSrc', e.message); } if (!cSource) { document.location = url; return false; } $('video, #mainVideo').attr('poster', response.poster); history.pushState(null, null, url); $('.topInfoTitle, title').text(response.title); $('#topInfo img').attr('src', response.userPhoto); $('#topInfo a').attr('href', response.url); modal.hidePleaseWait(); if ($('#modeYoutubeBottom').length) { $.ajax({ url: url, success: function (response) { modeYoutubeBottom = $(response).find('#modeYoutubeBottom').html(); $('#modeYoutubeBottom').html(modeYoutubeBottom); } }); } } } }); } } else if (isPlayerLoop()) { avideoToast("Looping video"); userIsControling = false; playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } } function formatBytes(bytes, decimals) { if (bytes == 0) return '0 Bytes'; var k = 1024, dm = decimals <= 0 ? 0 : decimals || 2, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } function tooglePlayerLoop() { setPlayerLoop(!isPlayerLoop()); } var setPlayerLoopSetTimeout; function setPlayerLoop(loop) { clearTimeout(setPlayerLoopSetTimeout); if (typeof player === 'undefined') { setPlayerLoopSetTimeout = setTimeout(function () { setPlayerLoop(loop) }, 1000); return false; } if (loop) { console.log("Loop ON"); //$.toast("Loop ON"); player.loop(1); $(".loop-button").removeClass('loop-disabled-button'); $(".loop-button, .loopButton").addClass('fa-spin'); } else { $(".loop-button").addClass('loop-disabled-button'); $(".loop-button, .loopButton").removeClass('fa-spin'); console.log("Loop OFF"); //$.toast("Loop OFF"); player.loop(0); } Cookies.set('playerLoop', loop, { path: '/', expires: 365 }); if (typeof setImageLoop === 'function') { setImageLoop(); } } function setImageLoop() { if (isPlayerLoop()) { $('.loopButton').removeClass('opacityBtn'); $('.loopButton').addClass('fa-spin'); } else { $('.loopButton').addClass('opacityBtn'); $('.loopButton').removeClass('fa-spin'); } } function toogleImageLoop(t) { tooglePlayerLoop(); if (typeof setImageLoop === 'function') { setImageLoop(); } } function isPlayerLoop() { if (typeof player === 'undefined') { return false; } var loop = Cookies.get('playerLoop'); if (!loop || loop === "false") { return player.loop(); } else { return true; } } function isArray(what) { return Object.prototype.toString.call(what) === '[object Array]'; } function reloadVideoJS() { if (typeof player.currentSources === 'function') { var src = player.currentSources(); player.src(src); } } var initdone = false; function setCurrentTime(currentTime) { console.log('setCurrentTime', currentTime); if (typeof player !== 'undefined') { if (isTryingToPlay) { if (currentTime <= player.currentTime()) { console.log('setCurrentTime is trying to play', currentTime); return false; // if is trying to play, only update if the time is greater } } player.currentTime(currentTime); initdone = false; // wait for video metadata to load, then set time player.on("loadedmetadata", function () { player.currentTime(currentTime); }); // iPhone/iPad need to play first, then set the time // events: https://www.w3.org/TR/html5/embedded-content-0.html#mediaevents player.on("canplaythrough", function () { if (!initdone) { player.currentTime(currentTime); initdone = true; } }); } else { setTimeout(function () { setCurrentTime(currentTime); }, 1000); } } function isALiveContent() { if (typeof isLive !== 'undefined' && isLive && (typeof isOnlineLabel === 'undefined' || isOnlineLabel === true)) { return true; } return false; } function isWebRTC() { if (typeof _isWebRTC !== 'undefined') { return _isWebRTC; } return false; } function isAutoplayEnabled() { //console.log("Cookies.get('autoplay')", Cookies.get('autoplay')); if (isWebRTC()) { console.log("isAutoplayEnabled said No because is WebRTC "); return false; } else if (isALiveContent()) { //console.log("isAutoplayEnabled always autoplay live contents"); return true; } else if ($("#autoplay").length && $("#autoplay").is(':visible')) { autoplay = $("#autoplay").is(":checked"); //console.log("isAutoplayEnabled #autoplay said " + ((autoplay) ? "Yes" : "No")); setAutoplay(autoplay); return autoplay; } else if ( typeof Cookies !== 'undefined' && typeof Cookies.get('autoplay') !== 'undefined' ) { if (Cookies.get('autoplay') === 'true' || Cookies.get('autoplay') == true) { //console.log("isAutoplayEnabled Cookie said Yes "); setAutoplay(true); return true; } else { //console.log("isAutoplayEnabled Cookie said No "); setAutoplay(false); return false; } } else { if (typeof autoplay !== 'undefined') { //console.log("isAutoplayEnabled autoplay said " + ((autoplay) ? "Yes" : "No")); setAutoplay(autoplay); return autoplay; } } setAutoplay(false); //console.log("isAutoplayEnabled Default is No "); return false; } function setAutoplay(value) { Cookies.set('autoplay', value, { path: '/', expires: 365 }); } function showAutoPlayVideoDiv() { var auto = $("#autoplay").prop('checked'); if (!auto) { $('#autoPlayVideoDiv').slideUp(); } else { $('#autoPlayVideoDiv').slideDown(); } } function enableAutoPlay() { setAutoplay(true); checkAutoPlay(); } function disableAutoPlay() { setAutoplay(false); checkAutoPlay(); } function checkAutoPlay() { if (isAutoplayEnabled()) { $("#autoplay").prop('checked', true); $('.autoplay-button').addClass('checked'); avideoTooltip(".autoplay-button", "Autoplay is ON"); } else { $("#autoplay").prop('checked', false); $('.autoplay-button').removeClass('checked'); avideoTooltip(".autoplay-button", "Autoplay is OFF"); } showAutoPlayVideoDiv(); } function isPlayNextEnabled() { if (isPlayerLoop()) { return false; } else if (isAutoplayEnabled()) { return true; } return false; } function avideoAlert(title, msg, type) { if (typeof msg !== 'string') { return false; } if (msg !== msg.replace(/<\/?[^>]+(>|$)/g, "")) {//it has HTML avideoAlertHTMLText(title, msg, type); } else { swal(title, msg, type); } } function _avideoToast(msg, icon) { var options = {text: msg, hideAfter: 7000}; if (icon) { options.icon = icon; } $.toast(options); } function avideoToast(msg) { _avideoToast(msg, null); } function avideoToastInfo(msg) { _avideoToast(msg, 'info'); } function avideoToastError(msg) { _avideoToast(msg, 'error'); } function avideoToastSuccess(msg) { _avideoToast(msg, 'success'); } function avideoToastWarning(msg) { _avideoToast(msg, 'warning'); } function avideoAlertAJAXHTML(url) { modal.showPleaseWait(); $.ajax({ url: url, success: function (response) { avideoAlertText(response); modal.hidePleaseWait(); } }); } function avideoAlertHTMLText(title, msg, type) { var span = document.createElement("span"); span.innerHTML = msg; swal({ title: title, content: span, icon: type, closeModal: true, buttons: type ? true : false, }); } function avideoModalIframe(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe'); } function avideoModalIframeSmall(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe-small'); } function avideoModalIframeLarge(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe-large'); } function avideoModalIframeWithClassName(url, className) { var span = document.createElement("span"); url = addGetParam(url, 'avideoIframe', 1); span.innerHTML = '