/**
  * Shorten a new URL
  *
  * @return Response
  */
 public function postShorten()
 {
     // No big url
     if (!\Input::has('bigurl')) {
         return \Response::json(array('error' => array('code' => 'MISSING-PARAMETERS', 'http_code' => '400', 'message' => 'Bad Request')), 400);
     }
     $bigURL = \Input::get('bigurl');
     $user = $this->apiKey->user;
     // No user linked to API key - SHOULD NEVER HAPPEN
     if (!isset($user)) {
         return \Response::json(array('error' => array('code' => 'NOT-AUTH', 'http_code' => '403', 'message' => 'Forbidden: SHOULD NEVER HAPPEN!')), 403);
     }
     // User has gone over quota so cant shorten
     if ($user->quota_max != 0 && $user->quota_used + 1 > $user->quota_max) {
         return \Response::json(array('error' => array('code' => 'QUOTA-USED', 'http_code' => '400', 'message' => 'Bad Request')), 403);
     }
     if (filter_var($bigURL, FILTER_VALIDATE_URL) === false) {
         return \Response::json(array('error' => array('code' => 'URL-INVALID', 'http_code' => '400', 'message' => 'Bad Request')), 400);
     }
     $dbLink = \Link::where('destination', '=', $bigURL)->first();
     if (!isset($dbLink)) {
         $dbLink = new \Link();
         $dbLink->user_id = $user->id;
         $dbLink->code = $dbLink->generateCode();
         $dbLink->destination = $bigURL;
         $dbLink->clicks = "0";
         $dbLink->save();
         $user->quota_used += 1;
         $user->save();
     }
     $linkCode = $dbLink->code;
     $linkURL = \Request::root() . '/' . $linkCode;
     return \Response::json(array('ok' => array('code' => 'LINK-SHORTENED', 'http_code' => '200', 'message' => 'OK', 'data' => array('url' => $linkURL, 'url_code' => $linkCode))), 200);
 }
 public function storeHref($href)
 {
     $model = Link::model()->find('href = ?', $href);
     $needToFetch = false;
     if ($model == null) {
         if ($model == null) {
             $model = new Link();
             $needToFetch = true;
         }
     } else {
         $content = $model->getHTMLContent();
         if (empty($content)) {
             $needToFetch = true;
         }
     }
     if ($needToFetch) {
         $content = file_get_contents($href);
         $model->href = $href;
         $model->provider = $this->_providerName;
         $model->type = $this->getType();
         $canonicalUrl = $this->getCanonicalUrl($content);
         if (!empty($canonicalUrl)) {
             $model->href = $canonicalUrl;
         }
         if ($model->validate()) {
             echo 'store URL : ' . $href . PHP_EOL;
             $model->save();
             $model->saveHTMLContent($content);
             return $model;
         }
     }
 }
 /**
  * Shorten a new URL
  *
  * @return Response
  */
 public function postShorten()
 {
     if (!\Auth::check()) {
         return \Response::json(array('error' => array('code' => 'NOT-AUTH', 'http_code' => '403', 'message' => 'Forbidden')), 403);
     }
     $shortenValidator = \Validator::make(\Input::all(), array('url' => 'required|url'));
     if ($shortenValidator->fails()) {
         return \Response::json(array('error' => array('code' => 'SHORTEN-VALIDATOR-FAILED', 'http_code' => '400', 'message' => 'Bad Request', 'data' => array('validator_messages' => $shortenValidator->messages()))), 400);
     }
     $bigURL = \Input::get('url');
     // User has gone over quota so cant shorten
     if (\Auth::user()->quota_max != 0 && \Auth::user()->quota_used + 1 > \Auth::user()->quota_max) {
         return \Response::json(array('error' => array('code' => 'QUOTA-USED', 'http_code' => '400', 'message' => 'Bad Request')), 403);
     }
     $dbLink = \Link::where('destination', '=', $bigURL)->first();
     if (!isset($dbLink)) {
         $dbLink = new \Link();
         $dbLink->user_id = \Auth::user()->id;
         $dbLink->code = $dbLink->generateCode();
         $dbLink->destination = $bigURL;
         $dbLink->clicks = "0";
         $dbLink->save();
         \Auth::user()->quota_used += 1;
         \Auth::user()->save();
     }
     $linkCode = $dbLink->code;
     $linkURL = \Request::root() . '/' . $linkCode;
     return \Response::json(array('ok' => array('code' => 'LINK-SHORTENED', 'http_code' => '200', 'message' => 'OK', 'data' => array('url' => $linkURL, 'url_code' => $linkCode))), 200);
 }
Exemple #4
0
 public function addLink($url, $user = null)
 {
     /** @var myModel $this */
     $link = new Link();
     $user = $user ?: \Phalcon\Di::getDefault()->get('auth');
     $link->save(['url' => $url, 'user_id' => $user->id, 'linkable_type' => get_class($this), 'linkable_id' => $this->id]);
     if (property_exists($this, 'linkCount')) {
         $this->increaseCount('linkCount');
     }
     return $this;
 }
Exemple #5
0
 public function run()
 {
     $model = new Link();
     if (isset($_POST['Link'])) {
         $model->attributes = $_POST['Link'];
         $model->logo = isset($_POST['logo']) ? $_POST['logo'] : '';
         if ($model->save()) {
             $this->controller->message('success', Yii::t('admin', 'Add Success'), $this->controller->createUrl('index'));
         }
     }
     $this->controller->render('create', array('model' => $model));
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Link();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Link'])) {
         $model->attributes = $_POST['Link'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Exemple #7
0
 /**
  * 录入
  *
  */
 public function actionCreate()
 {
     parent::_acl('link_create');
     $model = new Link();
     if (isset($_POST['Link'])) {
         $model->attributes = $_POST['Link'];
         if ($model->save()) {
             AdminLogger::_create(array('catalog' => 'create', 'intro' => '录入友情链接,ID:' . $model->id));
             $this->redirect(array('index'));
         }
     }
     $this->render('create', array('model' => $model));
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     if ($this->menu_use[12]) {
         $model = new Link();
         // Uncomment the following line if AJAX validation is needed
         // $this->performAjaxValidation($model);
         if (isset($_POST['Link'])) {
             $_POST['Link']['user_id'] = Yii::app()->user->id;
             $model->attributes = $_POST['Link'];
             if ($model->save()) {
                 $this->redirect(array('index'));
             }
         }
         $this->render('create', array('model' => $model));
     } else {
         $this->redirect(array('site/index'));
     }
 }
Exemple #9
0
 /**
  * 链接录入
  *
  */
 public function actionLinkCreate()
 {
     parent::_acl('link_create');
     $model = new Link();
     if (isset($_POST['Link'])) {
         $model->attributes = $_POST['Link'];
         $file = XUpload::upload($_FILES['attach']);
         if (is_array($file)) {
             $model->attach_file = $file['pathname'];
             $model->link_type = 'image';
         }
         if ($model->save()) {
             XXcache::refresh('_link');
             AdminLogger::_create(array('catalog' => 'create', 'intro' => '录入友情链接,ID:' . $model->id));
             $this->redirect(array('link'));
         }
     }
     $this->render('link_create', array('model' => $model));
 }
 /**
  * 添加新链接
  * 
  */
 public function actionCreate()
 {
     $model = new Link();
     if (isset($_POST['Link'])) {
         $model->attributes = $_POST['Link'];
         if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) {
             $upload = new Uploader();
             $upload->uploadFile($_FILES['logo']);
             if ($upload->_error) {
                 $this->message('error', Yii::t('admin', $upload->_error));
                 return;
             }
             $model->logo = $upload->_file_name;
         }
         if ($model->save()) {
             $this->redirect(array('index'));
         }
     }
     $this->render('create', array('model' => $model));
 }
 /**
  * Fills the course database with some required content and example content.
  * @param int Course (int) ID
  * @param string Course directory name (e.g. 'ABC')
  * @param string Language used for content (e.g. 'spanish')
  * @param bool Whether to fill the course with example content
  * @return bool False on error, true otherwise
  * @version 1.2
  * @assert (null, '', '', null) === false
  * @assert (1, 'ABC', null, null) === false
  * @assert (1, 'TEST', 'spanish', true) === true
  */
 public static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
 {
     if (is_null($fill_with_exemplary_content)) {
         $fill_with_exemplary_content = api_get_setting('course.example_material_course_creation') != 'false';
     }
     $course_id = intval($course_id);
     if (empty($course_id)) {
         return false;
     }
     $entityManager = Database::getManager();
     $course = $entityManager->getRepository('ChamiloCoreBundle:Course')->find($course_id);
     $tools = array();
     $settingsManager = CourseManager::getCourseSettingsManager();
     $settingsManager->setCourse($course);
     $toolList = CourseManager::getToolList();
     $toolList = $toolList->getTools();
     /** @var Chamilo\CourseBundle\Tool\BaseTool $tool */
     foreach ($toolList as $tool) {
         $visibility = self::string2binary(api_get_setting_in_list('course.active_tools_on_create', $tool->getName()));
         $toolObject = new CTool();
         $toolObject->setName($tool->getName())->setCategory($tool->getCategory())->setLink($tool->getLink())->setImage($tool->getImage())->setVisibility($visibility)->setAdmin(0)->setTarget($tool->getTarget());
         $tools[] = $toolObject;
         $settings = $settingsManager->loadSettings($tool->getName());
         $settingsManager->saveSettings($tool->getName(), $settings);
     }
     $course->setTools($tools);
     $entityManager->persist($course);
     $entityManager->flush($course);
     $courseInfo = api_get_course_info_by_id($course_id);
     $now = api_get_utc_datetime(time());
     $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST);
     $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
     $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
     $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
     $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
     $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
     $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
     $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
     $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
     $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION);
     $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
     $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
     $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
     $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
     $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
     $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
     $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
     $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
     $TABLEGRADEBOOKCERT = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
     $visible_for_all = 1;
     $visible_for_course_admin = 0;
     $visible_for_platform_admin = 2;
     /*    Course tools  */
     $alert = api_get_setting('exercise.email_alert_manager_on_new_quiz');
     if ($alert === 'true') {
         $defaultEmailExerciseAlert = 1;
     } else {
         $defaultEmailExerciseAlert = 0;
     }
     /* course_setting table (courseinfo tool)   */
     $settings = ['email_alert_manager_on_new_doc' => ['default' => 0, 'category' => 'work'], 'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'], 'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'], 'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'], 'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'], 'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'], 'course_theme' => ['default' => '', 'category' => 'theme'], 'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'], 'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'], 'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' => 'registration'], 'allow_user_view_user_list' => ['default' => 1, 'category' => 'user'], 'display_info_advance_inside_homecourse' => ['default' => 1, 'category' => 'thematic_advance'], 'email_alert_students_on_new_homework' => ['default' => 0, 'category' => 'work'], 'enable_lp_auto_launch' => ['default' => 0, 'category' => 'learning_path'], 'pdf_export_watermark_text' => ['default' => '', 'category' => 'learning_path'], 'allow_public_certificates' => ['default' => api_get_setting('course.allow_public_certificates') === 'true' ? 1 : '', 'category' => 'certificates'], 'documents_default_visibility' => ['default' => 'visible', 'category' => 'document']];
     /*$counter = 1;
       foreach ($settings as $variable => $setting) {
           Database::query(
               "INSERT INTO $TABLESETTING (id, c_id, variable, value, category)
                VALUES ($counter, $course_id, '".$variable."', '".$setting['default']."', '".$setting['category']."')"
           );
           $counter++;
       }*/
     /* Course homepage tools for platform admin only */
     /* Group tool */
     Database::query("INSERT INTO {$TABLEGROUPCATEGORIES}  (c_id, id, title , description, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order)\n             VALUES ({$course_id}, '2', '" . self::lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
     /*    Example Material  */
     $language_interface = !empty($language_interface) ? $language_interface : api_get_setting('language.platform_language');
     // Example material should be in the same language as the course is.
     $language_interface_original = $language_interface;
     $now = api_get_utc_datetime();
     $files = [['path' => '/shared_folder', 'title' => get_lang('UserFolders'), 'filetype' => 'folder', 'size' => 0], ['path' => '/chat_files', 'title' => get_lang('ChatFiles'), 'filetype' => 'folder', 'size' => 0]];
     $counter = 1;
     foreach ($files as $file) {
         self::insertDocument($course_id, $counter, $file);
         $counter++;
     }
     $sys_course_path = api_get_path(SYS_COURSE_PATH);
     $perm = api_get_permissions_for_new_directories();
     $perm_file = api_get_permissions_for_new_files();
     $chat_path = $sys_course_path . $course_repository . '/document/chat_files';
     if (!is_dir($chat_path)) {
         @mkdir($chat_path, api_get_permissions_for_new_directories());
     }
     /*    Documents   */
     if ($fill_with_exemplary_content) {
         $files = [['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0], ['path' => '/images/gallery', 'title' => get_lang('DefaultCourseImages'), 'filetype' => 'folder', 'size' => 0], ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0], ['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0], ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0], ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0]];
         foreach ($files as $file) {
             self::insertDocument($course_id, $counter, $file);
             $counter++;
         }
         // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
         $folders_to_copy_from_default_course = array('images', 'audio', 'flash', 'video', 'certificates');
         $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document/';
         $default_document_array = array();
         foreach ($folders_to_copy_from_default_course as $folder) {
             $default_course_folder_path = $default_course_path . $folder . '/';
             $files = self::browse_folders($default_course_folder_path, array(), $folder);
             $sorted_array = self::sort_pictures($files, 'dir');
             $sorted_array = array_merge($sorted_array, self::sort_pictures($files, 'file'));
             $default_document_array[$folder] = $sorted_array;
         }
         //Light protection (adding index.html in every document folder)
         $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n  </head>\n  <body>\n  </body>\n</html>";
         $example_cert_id = 0;
         if (is_array($default_document_array) && count($default_document_array) > 0) {
             foreach ($default_document_array as $media_type => $array_media) {
                 $path_documents = "/{$media_type}/";
                 //hack until feature #5242 is implemented
                 if ($media_type == 'images') {
                     $media_type = 'images/gallery';
                     $images_folder = $sys_course_path . $course_repository . "/document/images/";
                     if (!is_dir($images_folder)) {
                         //Creating index.html
                         mkdir($images_folder, $perm);
                         $fd = fopen($images_folder . 'index.html', 'w');
                         fwrite($fd, $htmlpage);
                         @chmod($images_folder . 'index.html', $perm_file);
                     }
                 }
                 $course_documents_folder = $sys_course_path . $course_repository . "/document/{$media_type}/";
                 $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document' . $path_documents;
                 if (!is_dir($course_documents_folder)) {
                     // Creating index.html
                     mkdir($course_documents_folder, $perm);
                     $fd = fopen($course_documents_folder . 'index.html', 'w');
                     fwrite($fd, $htmlpage);
                     @chmod($course_documents_folder . 'index.html', $perm_file);
                 }
                 if (is_array($array_media) && count($array_media) > 0) {
                     foreach ($array_media as $key => $value) {
                         if (isset($value['dir']) && !empty($value['dir'])) {
                             if (!is_dir($course_documents_folder . $value['dir'])) {
                                 //Creating folder
                                 mkdir($course_documents_folder . $value['dir'], $perm);
                                 //Creating index.html (for light protection)
                                 $index_html = $course_documents_folder . $value['dir'] . '/index.html';
                                 $fd = fopen($index_html, 'w');
                                 fwrite($fd, $htmlpage);
                                 @chmod($index_html, $perm_file);
                                 //Inserting folder in the DB
                                 $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1);
                                 $temp = explode('/', $folder_path);
                                 $title = $temp[count($temp) - 1];
                                 //hack until feature #5242 is implemented
                                 if ($title == 'gallery') {
                                     $title = get_lang('DefaultCourseImages');
                                 }
                                 if ($media_type == 'images/gallery') {
                                     $folder_path = 'gallery/' . $folder_path;
                                 }
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $folder_path . "','" . $title . "','folder','0')");
                                 $image_id = Database::insert_id();
                                 Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                        VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,0)");
                             }
                         }
                         if (isset($value['file']) && !empty($value['file'])) {
                             if (!file_exists($course_documents_folder . $value['file'])) {
                                 //Copying file
                                 copy($default_course_path . $value['file'], $course_documents_folder . $value['file']);
                                 chmod($course_documents_folder . $value['file'], $perm_file);
                                 //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
                                 $temp = explode('/', $value['file']);
                                 $file_size = filesize($course_documents_folder . $value['file']);
                                 //hack until feature #5242 is implemented
                                 if ($media_type == 'images/gallery') {
                                     $value["file"] = 'gallery/' . $value["file"];
                                 }
                                 //Inserting file in the DB
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $value["file"] . "','" . $temp[count($temp) - 1] . "','file','{$file_size}')");
                                 $image_id = Database::insert_id();
                                 if ($image_id) {
                                     $sql = "UPDATE {$TABLETOOLDOCUMENT} SET id = iid WHERE iid = {$image_id}";
                                     Database::query($sql);
                                     if ($path_documents . $value['file'] == '/certificates/default.html') {
                                         $example_cert_id = $image_id;
                                     }
                                     Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                            VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,1)");
                                     $docId = Database::insert_id();
                                     if ($docId) {
                                         $sql = "UPDATE {$TABLEITEMPROPERTY} SET id = iid WHERE iid = {$docId}";
                                         Database::query($sql);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $agenda = new Agenda();
         $agenda->setType('course');
         $agenda->set_course($courseInfo);
         $agenda->addEvent($now, $now, 0, get_lang('AgendaCreationTitle'), get_lang('AgendaCreationContenu'));
         /*  Links tool */
         $link = new Link();
         $link->setCourse($courseInfo);
         $links = [['c_id' => $course_id, 'url' => 'http://www.google.com', 'title' => 'Google', 'description' => get_lang('Google'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0], ['c_id' => $course_id, 'url' => 'http://www.wikipedia.org', 'title' => 'Wikipedia', 'description' => get_lang('Wikipedia'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0]];
         foreach ($links as $params) {
             $link->save($params);
         }
         /* Announcement tool */
         AnnouncementManager::add_announcement(get_lang('AnnouncementExampleTitle'), get_lang('AnnouncementEx'), ['everyone' => 'everyone'], null, null, $now);
         $manager = Database::getManager();
         /* Introduction text */
         $intro_text = '<p style="text-align: center;">
                         <img src="' . api_get_path(REL_CODE_PATH) . 'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
                         <h2>' . self::lang2db(get_lang('IntroductionText')) . '</h2>
                      </p>';
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_COURSE_HOMEPAGE)->setSessionId(0)->setIntroText($intro_text);
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_STUDENTPUBLICATION)->setSessionId(0)->setIntroText(get_lang('IntroductionTwo'));
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_WIKI)->setSessionId(0)->setIntroText(get_lang('IntroductionWiki'));
         $manager->persist($toolIntro);
         $manager->flush();
         /*  Exercise tool */
         $exercise = new Exercise($course_id);
         $exercise->exercise = get_lang('ExerciceEx');
         $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
                     <tr>
                     <td width="110" valign="top" align="left">
                         <img src="' . api_get_path(WEB_CODE_PATH) . 'default_course_document/images/mr_dokeos/thinking.jpg">
                     </td>
                     <td valign="top" align="left">' . get_lang('Antique') . '</td></tr>
                 </table>';
         $exercise->type = 1;
         $exercise->setRandom(0);
         $exercise->active = 1;
         $exercise->results_disabled = 0;
         $exercise->description = $html;
         $exercise->save();
         $exercise_id = $exercise->id;
         $question = new MultipleAnswer();
         $question->question = get_lang('SocraticIrony');
         $question->description = get_lang('ManyAnswers');
         $question->weighting = 10;
         $question->position = 1;
         $question->course = $courseInfo;
         $question->save($exercise_id);
         $questionId = $question->id;
         $answer = new Answer($questionId, $courseInfo['real_id']);
         $answer->createAnswer(get_lang('Ridiculise'), 0, get_lang('NoPsychology'), -5, 1);
         $answer->createAnswer(get_lang('AdmitError'), 0, get_lang('NoSeduction'), -5, 2);
         $answer->createAnswer(get_lang('Force'), 1, get_lang('Indeed'), 5, 3);
         $answer->createAnswer(get_lang('Contradiction'), 1, get_lang('NotFalse'), 5, 4);
         $answer->save();
         /* Forum tool */
         require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php';
         $params = ['forum_category_title' => get_lang('ExampleForumCategory'), 'forum_category_comment' => ''];
         $forumCategoryId = store_forumcategory($params, $courseInfo, false);
         $params = ['forum_category' => $forumCategoryId, 'forum_title' => get_lang('ExampleForum'), 'forum_comment' => '', 'default_view_type_group' => ['default_view_type' => 'flat']];
         $forumId = store_forum($params, $courseInfo, true);
         $forumInfo = get_forum_information($forumId, $courseInfo['real_id']);
         $params = ['post_title' => get_lang('ExampleThread'), 'forum_id' => $forumId, 'post_text' => get_lang('ExampleThreadContent'), 'calification_notebook_title' => '', 'numeric_calification' => '', 'weight_calification' => '', 'forum_category' => $forumCategoryId, 'thread_peer_qualify' => 0];
         store_thread($forumInfo, $params, $courseInfo, false);
         /* Gradebook tool */
         $course_code = $courseInfo['code'];
         // father gradebook
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',0,100,0,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',{$gbid},100,1,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOKLINK} (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked)\n                VALUES (1,{$exercise_id},1,'{$course_code}',{$gbid},'{$now}',100,1,0)");
     }
     //Installing plugins in course
     $app_plugin = new AppPlugin();
     $app_plugin->install_course_plugins($course_id);
     $language_interface = $language_interface_original;
     return true;
 }
Exemple #12
0
<?php

require '../../../lib/link.php';
require '../../../lib/id.php';
require '../../../lib/vote.php';
Link::set_db('sqlite:../../../heer.db');
Vote::set_db('sqlite:../../../heer.db');
ID::set_seed(file_get_contents('../../../seed'));
$url = $_GET['u'];
$title = $_GET['t'];
$bookmarklet = new ID($_GET['i']);
$vote = new Vote($url, $bookmarklet);
if ($_GET['n']) {
    $vote->note = $_GET['n'];
}
$link = new Link($url, $title);
if ($bookmarklet->isAuthentic() && $vote->save()) {
    $link->save();
}
header("Location: {$url}");
Exemple #13
0
function save_link($type, $size, $url, $nick, $saved_file)
{
    global $fetch_log;
    $title = $url;
    if (stristr($type, 'text/html') !== false && $size < FIVE_MEGS) {
        if (preg_match('!<title>(?<title>.*?)</title>!sim', file_get_contents($saved_file), $match)) {
            $title = html_entity_decode($match['title']);
        }
    }
    unlink($saved_file);
    if (ORM::all('link', array('url' => $url))->count() === 0) {
        $link = new Link(array('nick' => $nick, 'title' => $title, 'url' => $url, 'ctime' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME'])));
        $link->save();
    } else {
        file_put_contents($fetch_log, "[" . date('Y-m-d H:i:s') . "]\t{$nick}\tduplicate link\t{$url}\n", FILE_APPEND);
    }
}
Exemple #14
0
 public function postCreateLink()
 {
     if (Input::get('form') == 'form_main') {
         //var_dump(Input::all());
         $rules = array('name' => 'required|unique:links,name', 'img' => 'image|mimes:jpg,jpeg,png,gif', 'link' => 'required', 'descript' => 'required', 'middlecategories' => 'required');
         $validator = Validator::make(Input::all(), $rules);
         if ($validator->fails()) {
             return Redirect::to('/admin/link/create')->withErrors($validator)->withInput(Input::all());
         } else {
             $check = true;
             if (Input::hasFile('file')) {
                 $file = Input::file('img');
                 //$fileName = $file->getClientOriginalName();
                 $archivo = value(function () use($file) {
                     $filename = str_random(34) . '.' . $file->getClientOriginalExtension();
                     return strtolower($filename);
                 });
                 //var_dump($archivo);
                 $destinationPath = 'uploads/';
                 // Move file to generated folder
                 $check = $file->move($destinationPath, $archivo);
             }
             if ($check) {
                 $link = new Link();
                 $link->name = Input::get('name');
                 $link->link = Input::get('link');
                 $link->descript = Input::get('descript');
                 $link->img = NULL;
                 if (Input::hasFile('file')) {
                     $link->img = $archivo;
                 }
                 if (Input::get('gov')) {
                     $link->gov_id = Input::get('gov_id');
                 }
                 if (Input::get('middlecategories')) {
                     $link->middle_categories_id = Input::get('middlecategories');
                 } else {
                     $link->middle_categories_id = 3;
                 }
                 $link->frequency = 0;
                 $link->save();
                 /* @var \Elasticquent\ElasticquentTrait $link */
                 $link->addToIndex();
                 Session::flash('message', "สร้าง " . Input::get('name') . " สำเร็จ!!");
                 return Redirect::to('/admin/link/create');
             } else {
                 $messages = $validator->errors();
                 $messages->add('img', 'มีข้อผิดพลาดระหว่างการอัพโหลดรูป กรุณาลองอีกครั้ง');
                 return Redirect::to('/admin/link/create')->withErrors($messages)->withInput(Input::all());
             }
         }
     } else {
         if (Request::ajax() && Input::get('form') == 'form_uc') {
             $data = new UserCategories();
             $data->name = Input::get('name');
             $data->save();
         } else {
             if (Request::ajax() && Input::get('form') == 'form_mjc') {
                 $data = new MajorCategories();
                 $data->name = Input::get('name');
                 $data->user_categories_id = 6;
                 $data->save();
             } else {
                 if (Request::ajax() && Input::get('form') == 'form_mdc') {
                     $data = new MiddleCategories();
                     $data->name = Input::get('name');
                     $data->major_categories_id = 6;
                     $data->save();
                 }
             }
         }
     }
 }
 public function actionAddLink()
 {
     if (isset($_POST['dataset_id']) && isset($_POST['database']) && isset($_POST['acc_num'])) {
         // if(!is_numeric($_POST['acc_num'])) {
         // 	Util::returnJSON(array("success"=>false,"message"=>Yii::t("app", "Please enter a number.")));
         // }
         $linkVal = $_POST['database'] . ":" . $_POST['acc_num'];
         $link = Link::model()->findByAttributes(array('dataset_id' => $_POST['dataset_id'], 'link' => $linkVal));
         if ($link) {
             Util::returnJSON(array("success" => false, "message" => Yii::t("app", "This link has been added already.")));
         }
         $link = new Link();
         $link->dataset_id = $_POST['dataset_id'];
         $link->is_primary = true;
         $link->link = $linkVal;
         if ($link->save()) {
             Util::returnJSON(array("success" => true));
         }
         Util::returnJSON(array("success" => false, "message" => Yii::t("app", "Save Error.")));
     }
 }
Exemple #16
0
 /**
  * 创建对象
  * @param string $key
  * @param int $fileId
  * @param int $expirys
  * @param string $password
  * @return bool
  */
 public function createWithPassword($key, $fileId, $expirys, $password = "******")
 {
     $mode = Link::model()->find("share_key=:share_key", array("share_key" => $key));
     if (!isset($mode)) {
         $mode = new Link();
     }
     $mode->share_key = $key;
     $mode->file_id = $fileId;
     $mode->expiry = $expirys;
     $mode->password = $password;
     $mode->save();
     return true;
 }
Exemple #17
0
 /**
  * 
  * @param type $sid
  * @param type $data
  */
 protected function ghant_linksinserted($sid, $data)
 {
     $model = new Link();
     $model->target = isset($data['target']) ? $data['target'] : 0;
     $model->source = isset($data['source']) ? $data['source'] : 0;
     $model->type = isset($data['type']) ? $data['type'] : '';
     if ($model->save()) {
         $this->xmlOutputSuccess('inserted', $sid, $model->getPrimaryKey());
     } else {
         $this->xmlOutputError('Error crate link', $sid);
     }
 }
 public function addLink()
 {
     $image = Input::get('image');
     $site = Input::get('site');
     $data = array('image' => $image, 'site' => $site);
     $rules = array('image' => 'required|image', 'site' => 'required');
     $messages = array('required' => 1, 'image.image' => 2);
     $validation = Validator::make($data, $rules, $messages);
     if ($validation->fails()) {
         $number = $validation->messages()->all();
         if ($number[0]) {
             return Response::json(array('errCode' => 1, 'message' => '信息填写不完整!'));
         }
         return Response::json(array('errCode' => 2, 'message' => '必须为jpeg, png, bmp 或 gif的图片格式!'));
     }
     $link = new Link();
     $link->image = $image;
     $link->site = $site;
     if (!$link->save()) {
         return Response::json(array('errCode' => 3, 'message' => '添加失败!'));
     }
     return Response::json(array('errCode' => 0, 'message' => '添加成功!'));
 }
Exemple #19
0
 /**
  * Creates a link in the links tool from the given videoconference recording
  * @param int ID of the item in the plugin_bbb_meeting table
  * @param string Hash identifying the recording, as provided by the API
  * @return mixed ID of the newly created link, or false on error
  * @assert (null, null) === false
  * @assert (1, null) === false
  * @assert (null, 'abcdefabcdefabcdefabcdef') === false
  */
 public function copyRecordToLinkTool($id)
 {
     if (empty($id)) {
         return false;
     }
     //$records =  BigBlueButtonBN::getRecordingsUrl($id);
     $meetingData = Database::select('*', $this->table, array('where' => array('id = ?' => array($id))), 'first');
     $records = $this->api->getRecordingsWithXmlResponseArray(array('meetingId' => $meetingData['remote_id']));
     if (!empty($records)) {
         $count = 1;
         if (isset($records['message']) && !empty($records['message'])) {
             if ($records['messageKey'] == 'noRecordings') {
                 $recordArray[] = get_lang('NoRecording');
             } else {
                 //$recordArray[] = $records['message'];
             }
             return false;
         } else {
             $record = $records[0];
             if (is_array($record) && isset($record['recordId'])) {
                 $url = $record['playbackFormatUrl'];
                 $link = new Link();
                 $params['url'] = $url;
                 $params['title'] = $meetingData['meeting_name'];
                 $id = $link->save($params);
                 return $id;
             }
         }
     }
     return false;
 }
Exemple #20
0
 /**
  * Create \Link.
  * @see Validates input using the Violin class. https://github.com/alexgarrett/violin
  */
 private function create()
 {
     /** validate URL using Violin */
     $v = new \Violin\Violin();
     $v->validate(["url" => [$_POST["URL"], "required|url"]]);
     if ($v->passes()) {
         $url = $_POST["URL"];
         /** Check if Link is already in DB */
         $Link = Link::where("url", $url)->get();
         if ($Link->count()) {
             /** If so, just apply the old link. */
             $Link = $Link[0];
             $Link = $Link->getAttributes();
             $short = $Link["short"];
             /** Else, create a new Link */
         } else {
             $Link = new Link();
             $Link->url = $url;
             $Link->save();
             $short = $Link->short;
         }
         /** And shit it all out. */
         $this->render("New", ["short" => $this->getShortURL($short)]);
         /** Validation failed. */
     } else {
         $this->render("Home", ["error" => "Better check your URL!"]);
     }
 }
 public function createLink()
 {
     $link = new Link();
     $link->fill(Input::get('formdata'));
     $link->save();
     $link->sortorder = $link->id;
     $link->update();
     $html = View::make('projects.linkadmin')->withLink($link)->render();
     return $this->success(array('html' => $html), 'It worked');
 }
Exemple #22
0
 /**
  * Creates a link in the links tool from the given videoconference recording
  * @param int ID of the item in the plugin_bbb_meeting table
  * @param string Hash identifying the recording, as provided by the API
  * @return mixed ID of the newly created link, or false on error
  * @assert (null, null) === false
  * @assert (1, null) === false
  * @assert (null, 'abcdefabcdefabcdefabcdef') === false
  */
 function copy_record_to_link_tool($id, $record_id)
 {
     if (empty($id) or empty($record_id)) {
         return false;
     }
     $records = BigBlueButtonBN::getRecordingsArray($id, $this->url, $this->salt);
     if (!empty($records)) {
         foreach ($records as $record) {
             //error_log($record['recordID']);
             if ($record['recordID'] == $record_id) {
                 if (is_array($record) && isset($record['recordID']) && isset($record['playbacks'])) {
                     foreach ($record['playbacks'] as $item) {
                         $link = new Link();
                         $params['url'] = $item['url'];
                         $params['title'] = 'bbb 1';
                         $id = $link->save($params);
                         return $id;
                     }
                 }
             }
         }
     }
     return false;
 }
Exemple #23
0
 /**
  * @before _verified
  */
 public function createLink()
 {
     $this->JSONView();
     $view = $this->getActionView();
     $adid = RM::post("adid");
     if (!$adid) {
         return $view->set('message', "Invalid Request");
     }
     $ad = \Ad::first(["_id = ?" => $adid, "live = ?" => true], ['_id', 'title']);
     if (!$ad) {
         return $view->set('message', "Invalid Request");
     }
     $user = User::first(["id = ?" => RM::post("aff_id")]) ?? $this->user;
     $tdomains = Shared\Services\User::trackingLinks($user, $this->org);
     if (RM::post("domain")) {
         $domain = RM::post("domain");
     } else {
         $domain = $this->array_random($tdomains);
     }
     $link = Link::first(["ad_id = ?" => $ad->_id, "user_id = ?" => $user->_id], ['domain', '_id']);
     if (!$link) {
         $link = new Link(['user_id' => $user->_id, 'ad_id' => $ad->_id, 'domain' => $domain, 'live' => true]);
         $link->save();
     }
     $view->set('message', $ad->title)->set('link', $link->getUrl($domain));
 }
Exemple #24
0
 /**
  * 新建友情链接
  */
 public function actionCreatelink()
 {
     $modelLink = new Link();
     $successMessage = array();
     if (isset($_POST['Link'])) {
         $modelLink->attributes = $_POST['Link'];
         if ($modelLink->save()) {
             $this->redirect(array("admin", "type" => "link"));
         }
     }
     $this->render('admin', array("successMessage" => $successMessage, "modelLink" => $modelLink));
 }
Exemple #25
0
 /**
  * Creates a link in the links tool from the given videoconference recording
  * @param int ID of the item in the plugin_bbb_meeting table
  * @param string Hash identifying the recording, as provided by the API
  * @return mixed ID of the newly created link, or false on error
  * @assert (null, null) === false
  * @assert (1, null) === false
  * @assert (null, 'abcdefabcdefabcdefabcdef') === false
  */
 public function copy_record_to_link_tool($id, $record_id)
 {
     if (empty($id) or empty($record_id)) {
         return false;
     }
     require_once api_get_path(LIBRARY_PATH) . 'link.lib.php';
     $records = BigBlueButtonBN::getRecordingsArray($id, $this->url, $this->salt);
     if (!empty($records)) {
         foreach ($records as $record) {
             if ($record['recordID'] == $record_id) {
                 if (is_array($record) && isset($record['recordID']) && isset($record['playbacks'])) {
                     foreach ($record['playbacks'] as $item) {
                         $link = new Link();
                         $params['url'] = $item['url'];
                         $params['title'] = 'bbb 1';
                         $id = $link->save($params);
                         return $id;
                     }
                 }
             }
         }
     }
     return false;
 }
Exemple #26
0
 /**
  * Used to add a link or a category
  * @param string $type , "link" or "category"
  * @todo replace strings by constants
  * @author Patrick Cool <*****@*****.**>, Ghent University
  * @return bool True on success, false on failure
  */
 public static function addlinkcategory($type)
 {
     global $catlinkstatus;
     global $msgErr;
     $ok = true;
     $_course = api_get_course_info();
     $course_id = $_course['real_id'];
     $session_id = api_get_session_id();
     if ($type == 'link') {
         $tbl_link = Database::get_course_table(TABLE_LINK);
         $title = Security::remove_XSS(stripslashes($_POST['title']));
         $urllink = Security::remove_XSS($_POST['url']);
         $description = Security::remove_XSS($_POST['description']);
         $selectcategory = Security::remove_XSS($_POST['category_id']);
         if (!isset($_POST['on_homepage'])) {
             $onhomepage = 0;
         } else {
             $onhomepage = Security::remove_XSS($_POST['on_homepage']);
         }
         if (empty($_POST['target'])) {
             $target = '_self';
             // Default target.
         } else {
             $target = Security::remove_XSS($_POST['target']);
         }
         $urllink = trim($urllink);
         $title = trim($title);
         $description = trim($description);
         // We ensure URL to be absolute.
         if (strpos($urllink, '://') === false) {
             $urllink = 'http://' . $urllink;
         }
         // If the title is empty, we use the URL as title.
         if ($title == '') {
             $title = $urllink;
         }
         // If the URL is invalid, an error occurs.
         if (!api_valid_url($urllink, true)) {
             // A check against an absolute URL
             Display::addFlash(Display::return_message(get_lang('GiveURL'), 'error'));
             return false;
         } else {
             // Looking for the largest order number for this category.
             $link = new Link();
             $params = ['c_id' => $course_id, 'url' => $urllink, 'title' => $title, 'description' => $description, 'category_id' => $selectcategory, 'on_homepage' => $onhomepage, 'target' => $target, 'session_id' => $session_id];
             $link_id = $link->save($params);
             $catlinkstatus = get_lang('LinkAdded');
             if (api_get_setting('search_enabled') == 'true' && $link_id && extension_loaded('xapian')) {
                 require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
                 require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
                 require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
                 $course_int_id = $_course['real_id'];
                 $courseCode = $_course['code'];
                 $specific_fields = get_specific_field_list();
                 $ic_slide = new IndexableChunk();
                 // Add all terms to db.
                 $all_specific_terms = '';
                 foreach ($specific_fields as $specific_field) {
                     if (isset($_REQUEST[$specific_field['code']])) {
                         $sterms = trim($_REQUEST[$specific_field['code']]);
                         if (!empty($sterms)) {
                             $all_specific_terms .= ' ' . $sterms;
                             $sterms = explode(',', $sterms);
                             foreach ($sterms as $sterm) {
                                 $ic_slide->addTerm(trim($sterm), $specific_field['code']);
                                 add_specific_field_value($specific_field['id'], $courseCode, TOOL_LINK, $link_id, $sterm);
                             }
                         }
                     }
                 }
                 // Build the chunk to index.
                 $ic_slide->addValue('title', $title);
                 $ic_slide->addCourseId($courseCode);
                 $ic_slide->addToolId(TOOL_LINK);
                 $xapian_data = array(SE_COURSE_ID => $courseCode, SE_TOOL_ID => TOOL_LINK, SE_DATA => array('link_id' => (int) $link_id), SE_USER => (int) api_get_user_id());
                 $ic_slide->xapian_data = serialize($xapian_data);
                 $description = $all_specific_terms . ' ' . $description;
                 $ic_slide->addValue('content', $description);
                 // Add category name if set.
                 if (isset($selectcategory) && $selectcategory > 0) {
                     $table_link_category = Database::get_course_table(TABLE_LINK_CATEGORY);
                     $sql_cat = 'SELECT * FROM %s WHERE id=%d AND c_id = %d LIMIT 1';
                     $sql_cat = sprintf($sql_cat, $table_link_category, (int) $selectcategory, $course_int_id);
                     $result = Database::query($sql_cat);
                     if (Database::num_rows($result) == 1) {
                         $row = Database::fetch_array($result);
                         $ic_slide->addValue('category', $row['category_title']);
                     }
                 }
                 $di = new ChamiloIndexer();
                 isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : ($lang = 'english');
                 $di->connectDb(null, null, $lang);
                 $di->addChunk($ic_slide);
                 // Index and return search engine document id.
                 $did = $di->index();
                 if ($did) {
                     // Save it to db.
                     $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
                     $sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did)
                             VALUES (NULL , \'%s\', \'%s\', %s, %s)';
                     $sql = sprintf($sql, $tbl_se_ref, $course_int_id, $courseCode, TOOL_LINK, $link_id, $did);
                     Database::query($sql);
                 }
             }
             Display::addFlash(Display::return_message(get_lang('LinkAdded')));
         }
     } elseif ($type == 'category') {
         $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY);
         $category_title = trim($_POST['category_title']);
         $description = trim($_POST['description']);
         if (empty($category_title)) {
             $msgErr = get_lang('GiveCategoryName');
             Display::display_error_message(get_lang('GiveCategoryName'));
             $ok = false;
         } else {
             // Looking for the largest order number for this category.
             $result = Database::query("SELECT MAX(display_order) FROM  {$tbl_categories}\n                    WHERE c_id = {$course_id} ");
             list($orderMax) = Database::fetch_row($result);
             $order = $orderMax + 1;
             $order = intval($order);
             $session_id = api_get_session_id();
             $params = ['c_id' => $course_id, 'category_title' => $category_title, 'description' => $description, 'display_order' => $order, 'session_id' => $session_id];
             $linkId = Database::insert($tbl_categories, $params);
             if ($linkId) {
                 // iid
                 $sql = "UPDATE {$tbl_categories} SET id = iid WHERE iid = {$linkId}";
                 Database::query($sql);
                 // add link_category visibility
                 // course ID is taken from context in api_set_default_visibility
                 api_set_default_visibility($linkId, TOOL_LINK_CATEGORY);
             }
             Display::addFlash(Display::return_message(get_lang('CategoryAdded')));
         }
     }
     return $ok;
 }
Exemple #27
0
	public function addReplies()
	{
		$links=array();
		preg_match_all("/>&gt;&gt;\d+<\/a>/",$this->content,$matches);
		$matches=$matches[0];
		foreach($matches as $match)
		{
			// delete >> symbols
			$links[]=substr($match, 9, -4);
		}
		$posts=Post::model()->findAllByAttributes(array('board'=>$this->board,'vid'=>$links));
		foreach($posts as $post)
		{
			$link=new Link;
			$link->board=$this->board;
			$link->vid=$post->vid;
			$link->reply=$this->vid;
			$link->save();
		}
		return true;
	}